views:

154

answers:

3
ArrayList array = new ArrayList();

Iterator it1 = array.iterator();
while (it1.hasNext()){
   Myclass temp = it1.myGetterMethod();
   System.out.println (temp);
}

This is what I would like to implement, but Iterator only returns a generic Object. When I call Object.getClass(), the class is Myclass. Does this mean that the Iterator is not generic, and I need extend the Iterator class whenever I'm iterating objects that aren't Java strings etc?

+5  A: 

You did not create a generic ArrayList.

Try

ArrayList<MyClass> array = new ArrayList<MyClass>();

Iterator<MyClass> it1 = array.iterator(); 
while (it1.hasNext())
{ 
    MyClass temp = it1.myGetterMethod(); 
    System.out.println (temp); 
}
curlingdude
You need to genericize `Iterator` to `Iterator<MyClass>` as well, no? Or go straight to `for (MyClass c in array)`.
Michael Brewer-Davis
@Michael Brewer-Davis: It is done automatically for you, collections with generics will return corresponding iterators. It need to be declared correctly though.
Fredrik
@curlingdude: Now when your answer is accepted, maybe you should consider correcting it? You mix "MyClass" and "Myclass" and it is omitted completely in the "Iterator it1" declaration.
Fredrik
+4  A: 

Your code miss a few important things but the first thing you want to do is to either cast the value returned by Iterator.next() call (missing in your code) or use generics to have the compiler sort it out for you.

The two alternatives would look something like this (didn't try to compile them but they should be mostly right):

With cast:

ArrayList array = new ArrayList();
...    
Iterator it1 = array.iterator();
while (it1.hasNext()){
   Myclass temp = (Myclass)it1.next()
   System.out.println (temp);
}

With generics:

ArrayList<Myclass> array = new ArrayList<Myclass>();
...    
Iterator<Myclass> it1 = array.iterator();
while (it1.hasNext()){
   Myclass temp = it1.next()
   System.out.println (temp);
}

Edit: As someone else points out, using the foreach construct is in most cases preferable for readability. I decided to just modify your initial code as little as possible. A for construct would look like this:

ArrayList<Myclass> array = new ArrayList<Myclass>();
...    
for(Myclass temp : array){
   System.out.println (temp);
}
Fredrik
+5  A: 

Better to use the for statement and so hide the complexities of iterators. It is much easier to read

for (MyClass temp: array )
  {
  System.out.println (temp);
  }
Mark