我正在准备Java考试,其中有一道题让我花费了很长时间。尽管我努力学习,但我仍然无法找出结果顺序的确定方式。
请看一下:
class Country {
public enum Continent {
ASIA, EUROPE
}
String name;
Continent region;
public Country(String na, Continent reg) {
name = na;
region = reg;
}
public String getName() {
return name;
}
public Continent getRegion() {
return region;
}
}
public class OrderQuestion {
public static void main(String[] args) {
List<Country> couList = Arrays.asList(
new Country("Japan", Country.Continent.ASIA),
new Country("Italy", Country.Continent.EUROPE),
new Country("Germany", Country.Continent.EUROPE));
Map<Country.Continent, List<String>> regionNames = couList.stream()
.collect(Collectors.groupingBy(Country::getRegion,
Collectors.mapping(Country::getName, Collectors.toList())));
System.out.println(regionNames);
}
}
结果是什么?
A. {欧洲 = [意大利,德国],亚洲 = [日本]} B. {亚洲 = [日本],欧洲 = [意大利,德国]} C. {欧洲 = [德国,意大利],亚洲 = [日本]} D. {欧洲 = [德国],欧洲 = [意大利],亚洲 = [日本]}
最重要的是什么决定了具体的结果而不是其他结果?
Map
的 API 文档并了解其对元素顺序的说明。链接为 https://docs.oracle.com/javase/8/docs/api/java/util/Map.html - TesseractArrays.asList()
方法保证顺序,并且更多:返回一个由指定数组支持的固定大小列表。(对返回的列表进行的更改会直接反映到原数组中。)[...] 返回的列表是可序列化的并且实现了RandomAccess
接口。 - Andreas