集合迭代器Iterator与java.util.NoSuchElementException异常

1.在集合迭代器Iterator,中多次调用.next()方法有时会报该异常。
具体(猜想):
当集合元素为偶数个时,.next()方法为偶数(大于等于2)个时不会报异常,但会跳跃式读取元素
当集合元素为偶数个时,.next()方法为奇数个(大于2)时不会报该异常。

总结:Iterator中.next()方法只能调用一次,每一次使用都会指向下一个元素,当下一个元素不存在是(边界溢出)即报该错误

附录(代码Java):
1.

     m.put("0", new People("李明",19));
     m.put("1", new People("张红",17));
     m.put("2", new People("王梅",18));
     m.put("3", new People("孙丽",19));
     List<Map.Entry<String,People>> arr=new ArrayList<Map.Entry<String,People>>(m.entrySet());
     Collections.sort(arr,new MyCompare());    

//--------------------------------------------------------------------------------------------------
     Iterator<Map.Entry<String, People>> it1=arr.iterator();
     while(it1.hasNext()){
         String key=it1.next().getKey();
         System.out.println("名字:"+m.get(key).getName()+"   \t年龄:"+m.get(key).getAge());
         
     }

输出:    1名字:张红       年龄:17
    2名字:王梅       年龄:18
    3名字:孙丽       年龄:19
    0名字:李明       年龄:19

//---------------------------------------------------------------------------------------------------
     Iterator<Map.Entry<String, People>> it2=arr.iterator();
     while(it2.hasNext()){
         Entry<String, People> p=it2.next();
         System.out.println(p.getKey()+"名字:"+p.getValue().getName()+"   \t年龄:"+p.getValue().getAge());
     }
输出:    1名字:张红       年龄:17
    2名字:王梅       年龄:18
    3名字:孙丽       年龄:19
    0名字:李明       年龄:19

//---------------------------------------------------------------------------------------------------
  Iterator<Map.Entry<String, People>> it2=arr.iterator();
     while(it2.hasNext()){
         System.out.println(it2.next().getKey()+"名字:"+it2.next().getValue().getName()+"   \t年龄:"+it2.next().getValue().getAge());
     }
输出:
1名字:王梅       年龄:19
Exception in thread "main" java.util.NoSuchElementException

//----------------------------------------------------------------------------------------------------
Iterator<Map.Entry<String, People>> it2=arr.iterator();
 while(it2.hasNext()){
         System.out.println("名字:"+it2.next().getValue().getName()+"   \t年龄:"+it2.next().getValue().getAge());
     }
输出:
名字:张红       年龄:18
名字:孙丽       年龄:19
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值