如何在图中可视化java集合对象?与文字和书籍相比,我处理图片和视频的效果更好。
如果映射有键作为字符串,列表作为值。
上面的列表还有另一个自定义对象列表。
自定义对象有另一个列表。
这类场景经常出现在现实世界的项目中。
如何描绘和想象这些类型的场景来推进编码?
发布于 2021-10-16 12:03:18
想象一下这样一个例子。你的每个朋友都有他或她访问过的国家的名单。

键是String名称,值是List<Country>。
Map countriesVisited = new HashMap<String, List<Country>>();每个国家都有许多你的朋友访问过的城市。例如,李访问了乌克兰的基辅、奥德萨和利维夫。在基辅,他参观了三个名胜古迹:

代码如下。玩它看看它是如何工作的:
public class Travellers {
public static void main(String[] args) {
Country countryUkraine = new Country("Ukraine");
Map countriesVisited = new HashMap<String, List<Country>>();
countriesVisited.put("George", Arrays.asList(
new Country("Japan"), new Country("Brazil"), new Country("Poland"),
new Country("Croatia"), new Country("Nigeria"), new Country("Laos"),
new Country("Germany")
));
countriesVisited.put("Li", Arrays.asList(
new Country("Argentina"), countryUkraine, new Country("Italy"),
new Country("Great Britain"), new Country("Nepal")
));
countriesVisited.put("Keith", Arrays.asList(
new Country("Egypt"), new Country("Greece"), new Country("Lebanon"),
new Country("Marocco"), new Country("Saudi Arabia"), new Country("Kuwait")
));
countriesVisited.put("Jenny", Arrays.asList(
new Country("Norway"), new Country("Canada"), new Country("Russia"),
new Country("Antarctica"), new Country("Finland")
));
City cityKyiv = new City("Kyiv");
countryUkraine.setCities(Arrays.asList(
cityKyiv, new City("Odesa"), new City("Lviv")));
Place placeKyiv1 = new Place("Lavra");
Place placeKyiv2 = new Place("St Andrew’s Church");
Place placeKyiv3 = new Place("Museum of Folk Architecture");
cityKyiv.setPlaces(Arrays.asList(placeKyiv1, placeKyiv2, placeKyiv3));
System.out.println("Countries visited by George: " + countriesVisited.get("George"));
System.out.println("Countries visited by Li: " + countriesVisited.get("Li"));
System.out.println("Countries visited by Keith: " + countriesVisited.get("Keith"));
System.out.println("Countries visited by Jenny: " + countriesVisited.get("Jenny"));
System.out.println();
System.out.println("Cities visited by Li in Ukraine: " + countryUkraine.getCities());
System.out.println();
System.out.println("Places visited by Li in Kyiv: " + cityKyiv.getPlaces());
}
}
class Country {
String name;
List<City> cities;
Country(String name) {
this.name = name;
}
void setCities(List<City> cities) {
this.cities = cities;
}
List<City> getCities() {
return cities;
}
@Override public String toString() {
return name;
}
}
class City {
String name;
List<Place> places;
City(String name) {
this.name = name;
}
void setPlaces(List<Place> places) {
this.places = places;
}
List<Place> getPlaces() {
return places;
}
@Override public String toString() {
return name;
}
}
class Place {
String name;
int rating;
float latitude;
float longitude;
Image img;
Place(String name) {
this.name = name;
}
@Override public String toString() {
return name;
}
}https://stackoverflow.com/questions/69577708
复制相似问题