我正在准备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);
}
}
Run Code Online (Sandbox Code Playgroud)
结果是什么?
A. {EUROPE = [Italy, Germany], ASIA = [Japan]}
B. {ASIA = [Japan], EUROPE = [Italy, Germany]}
C. {EUROPE = [Germany, Italy], ASIA = [Japan]}
D. {EUROPE = [Germany], EUROPE = [Italy], ASIA = [Japan]}
什么最重要的是什么决定了具体的结果,而不是另一个?
我们可以消除,D因为Map中的键必须是唯一的,否则失败EUROPE.
我们可以C因为秩序而消除[Germany, Italy].在列表Italy中放置Germany,因此它也必须按结果列表中的顺序存储.
但是我们应该如何决定是否应该消除B或A?好吧,我们不能.
Map不保证键值对的特定顺序.有些映射允许记住像LinkedHashMap这样放置键值对的顺序,有些映射允许按TreeMap等键来排序条目,但是没有指定此行为Collectors.groupingBy.
事实证实,该方法正在使用HashMap,该方法基于密钥(Country.Continent此处为枚举)的hashCode()和已经保持的对的数量对键值对进行排序.hashCode()Enum的实现继承自Object类,这意味着它基于内存位置,每次运行JVM时都可以更改,因此它是随机值,阻止我们假设任何顺序(确认它未指定).
因此,基于缺少关于groupingBy两个条目顺序返回的Map的规范是可能的,因此A和B都是可能的答案.
| 归档时间: |
|
| 查看次数: |
277 次 |
| 最近记录: |