hashMap的一堆k-v放在HashMap$Node,其类型为EntrySet<entry>.而其中的k为set类型,v为collection类型。所以在遍历的时候,第一种方法是可以先取出key,用set的方法遍历key再找到value。第二种方法使直接用map的getValue,再用collection的方法遍历。第三种是通过EntrySet来获取k-v。具体实现代码如下:
public static void main(String[] args) {
HashMap hashMap = new HashMap();
hashMap.put("A","B");
hashMap.put("C","D");
//1.先提取key,再找value
Set keySet = hashMap.keySet();
//增强for
for (Object key :keySet) {
System.out.println(key +" loves "+ hashMap.get(key));
}
//iterator()
Iterator iterator = keySet.iterator();
while (iterator.hasNext()) {
Object key = iterator.next();
System.out.println(key +" loves "+ hashMap.get(key));
}
//2.用values后,用collection的遍历方法
//增强for
for (Object value : hashMap.values()) {
System.out.println(value);
}
//iterator
Iterator iterator1 = hashMap.values().iterator();
while (iterator1.hasNext()) {
Object value = iterator1.next();
System.out.println(value);
}
//3.通过 EntrySet,获取k-v:
Set entrySet = hashMap.entrySet();
//for:
for (Object entry :entrySet) {
//将entry转成 Map.Entry
Map.Entry mapEntry = (Map.Entry) entrySet;
System.out.println(mapEntry.getKey()+" loves "+mapEntry.getValue());
}
//iterator
while (iterator1.hasNext()) {
Object next = iterator1.next();
Map.Entry mapEntry = (Map.Entry) next;
System.out.println(mapEntry.getValue()+" loves "+mapEntry.getValue());
}
}