Java中的Iterator



1. 两种遍历方式:EntrySet 还是 KeySet


KeySet遍历两次:1)先遍历HashMap对象一次,得到key的Iterator;2)再根据key遍历一次,找到Vaule

EntrySet遍历一次: 遍历HashMap对象,得到Entry<key,value>;

详见:http://kim-miao.iteye.com/blog/736143


2. 小心死循环

下面这种写法会产生死循环

while(res.entrySet().iterator().hasNext()){
System.out.println("The probability of input feature classied to Class "
+res.entrySet().iterator().next().getKey()+ " is "
+res.entrySet().iterator().next().getValue());
}


改成如下:


Iterator<Entry<String, Float>> it = res.entrySet().iterator();
while(it.hasNext()){

System.out.println("The probability of input feature classied to Class "
+it.next().getKey()+ " is "
+it.next().getValue());
}
上面这种写法还是错的,一次循环中,it.next()执行两次,导致key和value匹配错误,必然导致最后一次it.next().getValue()失败,因为it已经迭代到最后了。

下面是正解:

Iterator<Entry<String, Float>> it = res.entrySet().iterator();
while(it.hasNext()){
Entry<String, Float> entry =  it.next();
System.out.println("The probability of input feature classied to Class "
+entry.getKey()+ " is "
+entry.getValue());
}


你可能感兴趣的:(Java中的Iterator)