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

查看:829
本文介绍了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 ?

先谢谢了。

推荐答案

有效的Java,第5章泛型,第25项:preFER名单阵列

从数组泛型类型在两个重要方面有所不同。首先,数组
  是协变的。这个可怕的冠冕堂皇的话只是意味着,如果SUB是
  超强的亚型,则数组类型子[]是超级[]的子类型。
  泛型,相反,是不变的:对于任何两个不同类型的类型1
  和 2型列表与LT;类型1> 既不是子类型,也不是超类型
  列表与LT; 2型> ...

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]。这意味着,阵列
  知道并在运行时执行它们的元素类型。如上述,如果注意到
  您尝试将字符串存储到长数组,你会得到一个
  ArrayStoreException信息。泛型,相比之下,通过擦除实现
  [JLS,4.6]。这意味着,他们只是执行自己的类型约束
  在编译时和放弃(或擦除)的元素类型的信息
  在运行时。擦除是允许泛型类型进行互操作
  自由与传统code不使用泛型(项目23)。因为
  这些根本性的分歧,数组和仿制药不拌匀。
  例如,它是非法的创建一个通用类型的数组,
  参数化类型或类型参数。这些阵列创建无
  前pressions是合法的,新的名单[],新名单[],新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.

长话短说:数组和泛型有一种对立的特点,这使得它非常困难的,如果在某些情况下不是不可能的,它们混合,所以最好把它约书亚·布洛克的话,用列表,而不是数组时,仿制药有涉及。

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天全站免登陆