检查对象实例的 ArrayList [英] Check ArrayList for instance of object

查看:22
本文介绍了检查对象实例的 ArrayList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 java 方法,它应该检查 ArrayList 并检查它是否包含给定类的实例.我需要将要检查的类的类型作为参数传递给方法,如果 List 包含给定类型的对象,则返回它.

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.

这能实现吗?

推荐答案

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

并打电话

String match = find(myArrayList, String.class);

这篇关于检查对象实例的 ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆