使用迭代器来操作ArrayList中的复杂对象?

时间:2014-07-08 10:03:52

标签: java iterator

我使用比较器通过id成功地对学生进行排序,并使用for循环显示,我希望知道如何使用iterator实现它,我试过但只尝试在控制台中解决,并且不知道如何从Student类打印信息

public static void main(String[] args) {
    Student stu1 = new Student("Lucy",1000,99);
    Student stu2 = new Student("Jack",1001,22);
    Student stu3 = new Student("Peter",1002,53);

    ArrayList<Student> student = new ArrayList<Student>();
    student.add(stu1);
    student.add(stu2);
    student.add(stu3);

    Collections.sort(student,new StuCOmp("id"));
    for (int i=0; i<student.size(); i++) {
        Student stu = student.get(i);
        System.out.println(stu.getName() + " "+stu.getId()+ " "+stu.getGrade());    
    }

    Iterator<Student> it = student.iterator();
    while(it.hasNext()){

        //what do I write here
    }
}

6 个答案:

答案 0 :(得分:1)

你可以在for循环中像这样迭代它 -

       for (Iterator<Student> iterator = student.iterator(); iterator.hasNext();) {
            Student stu = iterator.next();
            System.out.println(stu.getName() + " "+stu.getId()+ " "+stu.getGrade());
        }

答案 1 :(得分:1)

Iterator itr=student.iterator();  
  while(itr.hasNext()){  
    Student stu=(Student)itr.next();  
    System.out.println(stu.getName() + " "+stu.getId()+ " "+stu.getGrade());  

答案 2 :(得分:1)

Iterator<Student> it = student.iterator();
    while(it.hasNext()){
        // You should write here:   
        Student stu = it.next();
        System.out.println(stu.getName() + " "+stu.getId()+ " "+stu.getGrade());
     }

答案 3 :(得分:1)

您可以避免使用迭代器并使用增强的for循环。

for (Student st : student)
    System.out.println(st.getName() + " "+st.getId()+ " "+st.getGrade());

答案 4 :(得分:0)

你可以做这样的事情

Iterator<Student> it = student.iterator();
while(it.hasNext()){
  Student student=it.next();// you can get the students one by one  
  // Now you can get the each student info
  //student.any attribute
}

这种方式与for-each非常相似,但iterator比此更快。

答案 5 :(得分:0)

Iterator itr=student.iterator();  
  while(itr.hasNext()){  
    Student stu=(Student)itr.next();  
    System.out.println("whatever you want to print");