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

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

问题描述

我应该通过一个ArrayList检查,并检查它是否包含给定类的实例的Java方法。我需要通过该方法类的类型来检查作为参数,并且如果列表中包含的给定类型的一个对象,然后将其返回。

这是可以实现的?


解决方案

 公共静态< T>找不到(收集和LT;> ArrayList中,类< T> clazz所)
{
    对于(对象o:ArrayList中)
    {
        如果(O = NULL&放大器;!&安培; o.getClass()== clazz所)
        {
            返回clazz.cast(O);
        }
    }    返回null;
}

和电话

 字符串匹配=找到(myArrayList,为String.class);

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?

解决方案

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

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

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