Check ArrayList for instance of object

本秂侑毒 提交于 2019-11-30 05:17:38

问题


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?


回答1:


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



回答2:


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



回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/6350158/check-arraylist-for-instance-of-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!