Java泛型.泛型类型的数组 [英] Java Generics. Array of the generic type

查看:55
本文介绍了Java泛型.泛型类型的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始学习 JAVA 泛型.一切都说得通,我现在有点明白了.但是有一件事让我很不爽——你不能创建泛型类型的数组.

I recently started learning about JAVA generics. Everything made sense and I kinda understand them now. But one thing bugged me out - you cannot create array of the generic type.

我想实现抽象数据类型,例如队列和堆栈,但使用一些通用类型作为存储在堆栈中的底层数据.我将如何解决这个问题?我确定我失踪了,但它是什么?

I wanted to implement Abstract Data Types such as queue and stack, but with some generic type as the underlying data stored in the stack. How would I get around that ? I am sure I am missing but what it is ?

提前致谢.

推荐答案

Effective Java, CHAPTER 5 GENERICS, Item 25: Prefer Lists to arrays:

数组在两个重要方面不同于泛型.一、数组是协变的.这个听起来很吓人的词的意思很简单,如果 Sub 是一个Super 的子类型,那么数组类型 Sub[] 是 Super[] 的子类型.相比之下,泛型是不变的:对于任何两种不同的类型 Type1Type2, List 既不是子类型也不是超类型List ...

Arrays differ from generic types in two important ways. First, arrays are covariant. This scary-sounding word means simply that if Sub is a subtype of Super, then the array type Sub[] is a subtype of Super[]. Generics, by contrast, are invariant: for any two distinct types Type1 and Type2, List<Type1> is neither a subtype nor a supertype of List<Type2> ...

数组和数组的第二个主要区别泛型是数组被具体化 [JLS, 4.7].这意味着数组在运行时了解并强制执行它们的元素类型.如上所述,如果你尝试将一个 String 存储到一个 Long 数组中,你会得到一个数组存储异常.相比之下,泛型是通过擦除实现的[JLS,4.6].这意味着他们只强制执行他们的类型约束在编译时并丢弃(或擦除)它们的元素类型信息在运行时.擦除是允许泛型类型互操作的原因自由使用不使用泛型的遗留代码(条目 23).因为在这些基本差异中,数组和泛型不能很好地混合.例如,创建一个泛型类型的数组是非法的,一个参数化类型,或类型参数.这些数组创建都没有表达式是合法的:new List[]、new List[]、new E[].全部会在编译时导致通用数组创建错误.

The second major difference between arrays and generics is that arrays are reified [JLS, 4.7]. This means that arrays know and enforce their element types at runtime. As noted above, if you try to store a String into an array of Long, you’ll get an ArrayStoreException. Generics, by contrast, are implemented by erasure [JLS, 4.6]. This means that they enforce their type constraints only at compile time and discard (or erase) their element type information at runtime. Erasure is what allows generic types to interoperate freely with legacy code that does not use generics (Item 23). Because of these fundamental differences, arrays and generics do not mix well. For example, it is illegal to create an array of a generic type, a parameterized type, or a type parameter. None of these array creation expressions are legal: new List[], new List[], new E[]. All will result in generic array creation errors at compile time.

长话短说:数组和泛型具有某种相反"的特征,这使得在某些情况下很难(如果不是不可能的话)混合它们,因此最好听从 Joshua Bloch 的话,并在泛型时使用列表而不是数组都涉及到.

Long story short: Arrays and Generics have kind of "opposite" characteristics which makes it very difficult, if not impossible in some situations, to mix them, so better take Joshua Bloch's word on it and use Lists instead of arrays when generics are involves .

这篇关于Java泛型.泛型类型的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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