Linuxn00b Linuxn00b - 23 days ago 10
Java Question

Iterating Through a List of SubClasses (Java)

I'm trying to formulate a means of iterating an ArrayList of objects (3 of which are 3 different subclasses that extend the superclass). Is there a way to do this in Java? I can't think of a way to do it with instanceof. Thanks!

Answer

I'm not sure I entirely understand your question, but if you are trying to find all objects of a particular subclass in a superclass list the following code should work:

for(Object obj: lst) {
  if(obj instanceof mySubclass) {
    System.out.println("Found");
  }
}

If you want to iterate through the entire list the following will still work

  public static void helper(List<Animal> lst) {
  for(Animal animal: lst) {
      //Use listing code
  }
}