Q:

How to iterate a class in ArrayList?

import java.util.*;
class Animal{
String dog; String cat;
}
public class Arraylist {
 public static void main (String[] args) {

     Animal var=new Animal();
     var.dog="german";
     var.cat="persian";

     List <Animal> al=new ArrayList<Animal>();
     al.add(var);

     Iterator itr= al.listIterator();
     while(itr.hasNext())
     {System.out.print(", "+ itr.next());}
   }
}

now i would like to iterate the elements of the class. How could I do that?
Thanks!

A:

You are iterating over the elements of your class.
I see some potential issues though :

Rename your class from Arraylist to something else, less similar to java.util.ArrayList.
Change Iterator itr=... to Iterator<Animal> itr=...
If your Animal class doesn't override toString, it should. Otherwise System.out.print(", "+ itr.next()) won't print meaningful output.

Regarding the 3rd point. Add to your Animal class (and potentially to the sub-classes of this class, depending on what you wish to print) :
@Override
public String toString ()
{
    return "someStringThatRepresentsTheStateOfYourAnimalObject";
}

