Iterating through Arraylist with Extended Classes

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) { // this works, I want it shorter
            if (aObject instanceof B) {
                B b = (B) aObject;
                System.out.println (b.hi);
            }
        }
        for (B b : a) // like this?
            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.

+5
source share
4 answers

, FileFilter. (. korifey guava.) , . , , , List , . ( , .)

, - , . , ( , ) API.

+2

guava

:

for (B b: Iterables.filter(a, B.class)) {
 System.out.println (b.hi);
}
+2

JRSofty.

for (A aObject : a) {
    if (aObject instanceof B) { // <-- This is as short I can make it
        B b = (B) aObject;
        System.out.println (b.hi);
    }
}
0

:

for (A aObject : a)
    if (aObject instanceof B)
        System.out.println(((B) aObject).hi);

This is the best idea using an operator instanceof. But to filter list instances that are not of type B, you will need to integrate an additional collection library, since this operation is not directly supported by the standard collection API. Maybe Guava or LambdaJ support the type of filtering operation you want to do, I have not tested yet.

0
source

All Articles