I am wondering about a function in Java that I hope exists. I want to iterate through an Arraylist (say, class A) that contains objects of class B and C, which both extend A. The idea is, I only want to iterate over (for example) objects of class B into an ArrayList.
How is this possible, as a short example in the code below, and without a long one?
Main class:
import java.util.*;
public class Test {
public static void main(String[] args) {
new Test ();
}
Test() {
ArrayList<A> a = new ArrayList<A> ();
a.add (new B ());
a.add (new C ());
a.add (new C ());
a.add (new B ());
a.add (new C ());
for (A aObject : a) {
if (aObject instanceof B) {
B b = (B) aObject;
System.out.println (b.hi);
}
}
for (B b : a)
System.out.println (b.hi);
}
}
AND:
public class A {
}
AT:
public class B extends A {
String hi = "hi";
}
WITH
public class C extends A {
}
EDIT: Because so many people answer this: I know about using instanceof. I want a faster way to iterate over all the objects in an array, of which class B.
Hidde source
share