我有点困惑。我正在阅读 map 界面。它必须使用 Collection View 的entrySet()方法才能使用迭代器。 EntrySet()返回一个包含map元素的Set。同样,每个 Set 元素都是一个 Map.Entry 对象。这怎么可能?因为Set只包含一个字段,而Map.Entry是一个键值对?
最佳答案
map 基本上是一组key => value
映射。此外,键是唯一的,而值不必是唯一的。键值对封装在 Map.Entry
中目的。当您迭代映射的条目(= 键值对集)时,对于每个 entry
您可以通过 entry.getKey()
获取 key 以及 entry.getValue()
的值.
除了条目集之外,映射还提供键集和值集合。例如,在Map<String, Date>
中,您的键值对集为 Set<Map.Entry<String, Date>>
,键集为Set<String>
值的集合为 Collection<Date>
.
迭代条目的具体示例:
Map<String, Date> map = new HashMap<String, Date>();
map.put("now", new Date());
map.put("now+", new Date());
for (Map.Entry<String, Date> entry : map.entrySet()) {
String key = entry.getKey();
Date value = entry.getValue();
System.out.println(String.format("%s => %s", key, value));
}
另一种迭代方式是通过键:
for (String key : map.keySet()) {
Date value = map.get(key);
System.out.println(String.format("%s => %s", key, value));
}
但这效率较低,因为与使用直接访问值的条目相比,您必须对每个键执行查找才能获取值。
关于java - Set 中的每个元素如何成为 Map.Entry 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21795515/