Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 366
Danny Avatar asked Jun 14 '11 21:06

Danny


People also ask

How do you check if an object is an instance of an ArrayList?

To check if ArrayList contains a specific object or element, use ArrayList. contains() method. You can call contains() method on the ArrayList, with the element passed as argument to the method. contains() method returns true if the object is present in the list, else the method returns false.

How do I find the instance of a list?

This could be used if you want to check that object is instance of List<T> , which is not empty: if(object instanceof List){ if(((List)object). size()>0 && (((List)object). get(0) instanceof MyObject)){ // The object is of List<MyObject> and is not empty.

Is ArrayList an instance of collection?

ArrayList is a part of the Java collection framework and it is a class of java.

How do you check if an item is in an ArrayList Java?

We can check whether an element exists in ArrayList in java in two ways: Using contains() method. Using indexOf() method.


2 Answers

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);
like image 117
Bala R Avatar answered Oct 18 '22 07:10

Bala R


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;
}
like image 35
jimr Avatar answered Oct 18 '22 07:10

jimr