Check ArrayList for instance of object

Viewed 22656

I have a java method that should check through an ArrayList and check if it contains an instance of a given class. I need to pass the method the type of class to check for as a parameter, and if the List contains an object of the given type, then return it.

Is this achievable?

5 Answers

check one of the the item instance in the list

if (object instanceof ArrayList<?>) {
                        if (((ArrayList<?>) object).get(0) instanceof ClassA) {
                            classAList= (ArrayList<ClassA>) object;
                        } else if (((ArrayList<?>) object).get(0) instanceof ClassB) {
                            classBList= (ArrayList<classB>) object;
                        } else if (((ArrayList<?>) object).get(0) instanceof ClassC) {
                            classCList= (ArrayList<ClassC>) object;
                        }
                    }
Related