gpt4 book ai didi

Java 泛型。泛型类型的数组

转载 作者:太空宇宙 更新时间:2023-11-04 07:04:06 24 4
gpt4 key购买 nike

我最近开始学习JAVA泛型。一切都有意义,我现在有点理解它们了。但有一件事让我烦恼 - 你不能创建泛型类型的数组。

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

提前致谢。

最佳答案

Effective Java,第 5 章泛型,第 25 项:优先使用列表而不是数组:

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> ...

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 的话,在涉及泛型时使用列表而不是数组。

关于Java 泛型。泛型类型的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21664875/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com