-1

I am learning java right now. While writing code for traversing ArrayList using Iterator I have to use the class name before using the iterator's object with next() function. Can anybody help me with this?

import java.util.*;

public class arraylistwithuserdefinedclass {
    public static void main(String[] args) {    
        ArrayList<UserId> details=new ArrayList<UserId>();
        UserId a=  new UserId(22,"gurmeet");    
        UserId b=  new UserId(24,"sukhmeet");
        details.add(a);
        details.add(b);
        Iterator itr = details.iterator();
        while(itr.hasNext()) {    
            UserId ui = (UserId) itr.next();
            System.out.println(ui.age +" " + "" + ui.name) ;
        }
    }       
}

class UserId {
    int age;
    String name;
    UserId(int a, String b) {
        age=a;
        name=b;
    }
}
Arun Sudhakaran
  • 2,167
  • 4
  • 27
  • 52
GURMEET SINGH
  • 111
  • 14

3 Answers3

4

Make your Iterator UserId type (specify the type), ie

Iterator<UserId> itr = details.iterator();

Because if you don't specify the type, how will it understand what to return. So for generalized purpose it will return Object type and thats why downcasting is required.

Arun Sudhakaran
  • 2,167
  • 4
  • 27
  • 52
2

You have to specify the generic type for the Iterator because without this type the Iterator holds type Object :

Iterator itr = details.iterator();// This holds type Object.

for that it is required to cast every Object.


another reference :

it.next() Returns the next object. If a generic list is being accessed, the iterator will return something of the list's type. Pre-generic Java iterators always returned type Object, so a downcast was usually required.


it is not required if you set the type for the Iterator :

Iterator<UserId> itr = details.iterator();
//         ^^--------------------------

So you can use without casting :

while (itr.hasNext()) {
    UserId ui = itr.next();
//-------------^
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
1

Your iterator is declared raw, that is the reason why you need to cast, do instead declare the iterator as a UserId doing Iterator<UserId>

Iterator<UserId> itr = details.iterator();
    while(itr.hasNext()) {
        ...
        UserId ui = (UserId)
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97