9

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?

0

5 Answers 5

19
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);
Sign up to request clarification or add additional context in comments.

2 Comments

You need to use Class.isAssignableFrom to handle subclasses, also the method should take Collection instead of ArrayList (ie, program to the interface). Also consider using Java's recommended coding standard of making method names start with lowercase.
@Steve Kuo: or Class.isInstance
5
public static <T> T getFirstElementOfTypeIn( List<?> list, Class<T> clazz )
{
  for ( Object o : list )
  {
    if ( clazz.isAssignableFrom( o.getClass() ) )
    {
      return clazz.cast( o );
    }
  }
  return null;
}

1 Comment

clazz.isAssignableFrom( o.getClass() ) can be written as clazz.isInstance( o )
1

If you're using Java 8 you can do:

public <T> Optional<T> getInstanceOf(Class<T> clazz, Collection<?> collection) {
    return (Optional<T>) collection.stream()
            .filter(e -> clazz.isInstance(e.getClass()))
            .findFirst();
}

Check the documentation of Optional if you never used it before. Actually this is better practice than returning null.

Comments

0

You can iterator over your list and test each element

Class<?> zz = String.class;
for (Object obj : list) {
    if (zz.isInstance(obj)) {
        System.out.println("Yes it is a string");
    }
}

Note that isInstance also captures subclasses. Otherwise see Bela`s answer.

1 Comment

This has been down voted, but seems to be the better solution where you are unconcerned with subclasses of the class or subclass you're checking; as in my case, and as the post explains. So why the down vote? If no good explanation can be given, I'm up voting.
0

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;
                        }
                    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.