Check ArrayList for instance of object

前端 未结 5 1332
南方客
南方客 2021-01-02 11:57

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 a

5条回答
  •  灰色年华
    2021-01-02 12:34

    public static  T find(Collection arrayList, Class 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);
    

提交回复
热议问题