0
ArrayList<Student> al = new ArrayList<Student>();
Iterator itr = al.iterator(); 
while (itr.hasNext())
{  
    Student st = (Student) itr.next();
    System.out.println(st.rollno+" "+st.name+""+st.age);                                                  
}

Assume Student class having three data members rollno,name and age. So,my question is why we downcast in the statement Student st=(Student)itr.next(); But if we make an ArrayList having String as types of data members,then there is no need to downcast it using iterator again. Please help to clear my doubt.

Michael Markidis
  • 4,163
  • 1
  • 14
  • 21
  • 1
    IIRC `al.iterator()` would return a `Iterator` so there's no need for the cast. It's only needed because you removed the generics from `Iterator itr`. Btw, the same would be true for `ArrayList`, if you experience different results you most likely have different code (e.g. you're using `Iterator` in that case). – Thomas Jun 21 '16 at 14:58
  • You could just change `Iterator itr` to `Iterator itr`. – Zircon Jun 21 '16 at 14:59
  • I believe you still have to cast : `String st = (String)itr.next();` otherwise it won't compile. How did you assume that you don't need to cast if the type of object in the list is String – SomeDude Jun 21 '16 at 15:00

2 Answers2

3

That's because you're using a raw Iterator.

Parametrize your Iterator as such: Iterator<Student> itr=al.iterator();

Then you won't have to explicitly cast the next invocation (returning Object when raw) to Student.

You can also spare yourself the clutter if you're just iterating and printing, and use fast enumeration instead:

for (Student s: al) {
    // print stuff
}
Mena
  • 47,782
  • 11
  • 87
  • 106
1

Iterator can take advantage of generics, so you can have an Iterator<Student> that will return a Student instance when invoking next().

Actually al.iterator() is already returning an Iterator<Student>, you're just erasing its generics by assigning it to a raw Iterator.

Check out this related question: Iterator vs Iterator in java.

Community
  • 1
  • 1
Xavi López
  • 27,550
  • 11
  • 97
  • 161