-1

I'm practicing ArrayList program. I would like to ask the meaning of this line.

Student st = (Student)itr.next();

    public static void main(String[] args) {

        Student s1 = new Student(1,"owelcute",28);
        Student s2 = new Student(2,"lucas",2);
        Student s3 = new Student(3,"jor",30);

        ArrayList <Student> studentList = new ArrayList<Student>();
        /*
        declaring class Student in ArrayList
         */

        studentList.add(s1);
        studentList.add(s2);
        studentList.add(s3);

        Iterator itr = studentList.iterator();

        while(itr.hasNext()){

            Student st = (Student)itr.next();
            System.out.println(st.rollno + " "+ st.name + " "+ st.age);
        }

    }
lczapski
  • 4,026
  • 3
  • 16
  • 32
Owel
  • 1
  • 1
    Always read the [javadoc](https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html#next--). If you are using a good IDE, you can just hover over "next()" to view it. – Kartik Oct 18 '19 at 01:14

2 Answers2

1
Student st 

creates a variable st that is type student.

=(Student)itr.next();

sets st to the value of the next element that itr(the iterator) is pointing to. (Student) is a cast that ensures

itr.next();

is of type Student.

KanekiUchiha
  • 117
  • 7
0

This is explained in the doc for iterator.next: it gets the next item in the iteration.

If the casting (Student) confuses you then that is partly because the code is incorrectly using the raw Iterator type.

The code should be, more correctly:

Iterator<Student> iterator = studentList.iterator();
while (iterator.hasNext()) {
    Student student = iterator.next();
    ...
}

Or, even better:

for (Student student: studentList) {
    ...
}
sprinter
  • 27,148
  • 6
  • 47
  • 78