Check if an object is of the same type as the passed one

I have class A and two classes B and C which extend A. I have an array list which contains multiple instances of all of these classes. Can I have a method which takes in an object and returns all objects in the array list which is of the same type as the one given to the method and how would I go about doing this?

Jon Skeet
people
quotationmark

Sure - you'd use getClass() to find the execution-time type:

private final List<A> allKnownValues = ...;

List<A> getAllValuesOfTheSameType(A sample) {
    ArrayList<A> results = new ArrayList<>();
    for (A candidate : allKnownValues) {
        if (candidate.getClass() == sample.getClass()) {
            results.add(candidate);
        }
    }
    return results;
}

If you want to include subtypes, you could use:

if (sample.getClass().isInstance(candidate))

people

See more on this question at Stackoverflow