如何使用声明Class对象的指定类型的ArrayList中 [英] How to declare an ArrayList of specified type using Class object

查看:989
本文介绍了如何使用声明Class对象的指定类型的ArrayList中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想一类对象传递给函数然后声明类类型的ArrayList中。我想知道我是如何做到这一点。

 公共静态无效CreateList(C类){
    //我想用变量c来定义它的类型来创建这个数组列表
    的ArrayList&所述c取代;名单=新的ArrayList();
}


解决方案

您可以泛化的类< T> ,然后用 T

 公共静态< T>无效createList(类< T>的cls){
    ArrayList的< T> =新的ArrayList<>();
}

要扩大,如果你需要找到一个类及其子类的所有实例,或者,从列表中,并作为一个列表返回结果值,你可以这样做:

 公共静态< T>清单< T> filterInstancesOf(列表<>原来,类< T>的cls){
    清单< T> RV =新的ArrayList<>();
    对于(对象o:原创){
        如果(cls.isInstance(O)){
            rv.add(cls.cast(O));
        }
    }
    返回rv;
}

有人建议,这不能做,而且没有意义的事,但它确实有非常多的感觉。

也有人认为原创参数使用有限制类型,比如名单,LT ;?超级T> 。同样,这将是无用的,它不会增加的类型安全,但实际上渲染方法本身不太有用。

因为它是现在,你可以使用的方法来筛选实现一个接口,例如情况下,假设我们有

 列表< SomeClass的>善堂;
...
filterInstancesOf(LST,Serializable.class);

如果该方法使用有限的类型,这不能被使用,因为 SomeClass的不是序列化的超

I want to pass a Class object to a function then declare a ArrayList of the type that class is. I am wondering how I do this.

public static void CreateList(Class c){
    // I want to create this array list using the variable c to define its type
    ArrayList<c> list = new ArrayList();
}

解决方案

You can genericize the Class to Class<T> and then use T:

public static <T> void createList(Class<T> cls) {
    ArrayList<T> = new ArrayList<>();
}

To expand, if you need to find the all instances of a class, or its subclasses, from a list and return the resulting values as a list, you can do:

public static <T> List<T> filterInstancesOf(List<?> original, Class<T> cls) {
    List<T> rv = new ArrayList<>();
    for (Object o: original) {
        if (cls.isInstance(o)) {
            rv.add(cls.cast(o));
        }
    }
    return rv;
}

There were suggestions that this cannot be done, and does not make sense to do, but it does have very much sense.

It was also suggested that the original parameter use a bounded type, say List<? super T>. Again this would be useless, it would not add to the type safety, but actually render the method itself less useful.

As it is now, you can use the method to filter instances that implement an interface, for example, assuming we have

List<SomeClass> lst;
...
filterInstancesOf(lst, Serializable.class);

If the method used bounded types, this could not be used, as SomeClass is not the superclass of Serializable.

这篇关于如何使用声明Class对象的指定类型的ArrayList中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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