S_Clegane 2019-03-14 20:13 采纳率: 100%
浏览 432
已采纳

各位JAVA前辈,迭代器使用报错。

定义一个Student类,
类中封装了三个成员变量String name,int age,double score。
在测试类主方法中创建了几个Student类的对象,并添加到ArrrayList集合中。
使用Iterator迭代出对象中的成员变量。

部分代码如下

        Iterator<Students> it = st.iterator();
            while (it.hasNext()){
               Students s =  it.next();
//                System.out.print(s.getName()+" ");
//                System.out.print(s.getAge()+" ");
//                System.out.print(s.getScore()+" ");
//                System.out.println();
                System.out.println(it.next().getName());
                System.out.println(it.next().getAge());
                System.out.println(it.next().getScore());

            }

如果使用未注释的方法,报错,如果使用注释的方法报错。
请问为什么,这两种方式不应该是等价的么?

  • 写回答

1条回答 默认 最新

  • 毕小宝 领域专家: 后端开发技术领域 2019-03-15 10:11
    关注

    首先,楼上的说法错误,因为Iterator已经指定类型为Student了,所以不需要类型转换。
    其次,你需要明白it.next()操作是在遍历迭代器,调用一次,就迭代一条数据。你未曾注释的代码中总共有四次it.next()相当于操作了列表中的四个元素,如果列表中元素少于四个,就会报越界错误或者空指针错误。
    第三,未注释的写法是错误的,正确的用法应该是:

    while (it.hasNext()){
                   Students s =  it.next();
                                 if(s==null){
                                     continue;//判空
                                 }
                                 System.out.print(s.getName()+" ");
                   System.out.print(s.getAge()+" ");
                    System.out.print(s.getScore()+" ");
                    System.out.println();
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?