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?
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.
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.
ArrayList is a part of the Java collection framework and it is a class of java.
We can check whether an element exists in ArrayList in java in two ways: Using contains() method. Using indexOf() method.
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);
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With