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());
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值