加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

如何在java中使用数组类型泛型?

发布时间:2020-12-15 04:21:18 所属栏目:Java 来源:网络整理
导读:在 java中,我想创建一个函数,它接受任何类型的内容列表,然后返回相同类型的数组.我到目前为止 public static T[] listToArray(ListT items) { T[] names = new T[items.size()]; for(int i=0; iitems.size(); i+=1) { names[i] = items.get(i); } return nam
在 java中,我想创建一个函数,它接受任何类型的内容列表,然后返回相同类型的数组.我到目前为止

public static <T>[] listToArray(List<T> items) {
    <T>[] names = new <T>[items.size()];
    for(int i=0; i<items.size(); i+=1) {
        names[i] = items.get(i);
    }
    return names;
}

但这有很多语法错误……

有谁知道如何做到这一点?

谢谢

解决方法

来自Bloch的Effective Java,第25项:

…arrays and generics have very different type rules. Arrays are
covariant and reified; generics are invariant and erased. As a
consequence,arrays provide runtime type safety but not compile-time
type safety and vice versa for generics. Generally speaking,arrays
and generics don’t mix well. If you find yourself mixing them and
getting compile-time errors or warnings,your first impulse should be
to replace the arrays with lists.

说明:

数组是协变意味着如果类Dog扩展了类Animal,那么你可以这样做:

Animal[] animals = new Animal[5];
animals[0] = new Dog();

同样不适用于泛型,因为泛型是不变的:

List<Animal> animals = new LinkedList<Animal>();
animals.add(new Dog()); // compilation error!!!

数组的实现意味着有关数组类型的所有信息在运行时和编译时都可用.同样,泛型被擦除,这意味着类型信息仅在编译期间存在.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读