Danny Danny - 4 years ago 468
Java Question

Check ArrayList for instance of object

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?

Answer Source
public static <T> T find(Collection<?> arrayList, Class<T> clazz)
    for(Object o : arrayList)
        if (o != null && o.getClass() == clazz)
            return clazz.cast(o);

    return null;    

and call

String match = find(myArrayList, String.class);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download