我有点困惑。我在阅读地图接口时,发现必须使用entrySet()方法来获取集合视图以使用迭代器。entrySet()返回一个包含map元素的set。同样,此set中的每个元素都是一个Map.Entry对象。这怎么可能呢?因为Set只包含一个字段,而Map.Entry是一个键值对。
我有点困惑。我在阅读地图接口时,发现必须使用entrySet()方法来获取集合视图以使用迭代器。entrySet()返回一个包含map元素的set。同样,此set中的每个元素都是一个Map.Entry对象。这怎么可能呢?因为Set只包含一个字段,而Map.Entry是一个键值对。
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));
}
但这种方法不够高效,因为对于每个键,您都必须执行查找以获取值,与使用直接访问值的条目相比。
集合元素是对象,Map.Entry实例也是一个对象。一切正确。
Cat
类,并添加所需属性。例如:public class Cat {
private String name;
private String type;
private boolean isGrumpy;
// etc...
}
equals(Object)
和hashCode()
,这个类的实例就可以放在Set
中,是吗?Map.Entry
应该不同呢?只需将其视为具有两个成员-key
和value
的类即可。
Map.Entry
。没有什么神秘的 ;) - fge