eclipse 堆栈数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/838439/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-19 13:41:54  来源:igfitidea点击:

array of stacks

javaeclipsearraysgenerics

提问by harto

Is it possible to create an array of stacks without having to cast the stacks as they come out? Eclipse gives me a warning about not being able to make a generic array of Stack when I do something like this:

是否可以创建一个堆栈数组而不必在堆栈出现时进行转换?当我执行以下操作时,Eclipse 会警告我无法创建通用的 Stack 数组:

Stack<Card>[] cards = new Stack<Card>[52];

回答by harto

Joshua Bloch does an excellent job of describing this problem in Effective Java, Second Edition. Check out the relevant section on Google Book Search.

Joshua Bloch 在Effective Java, Second Edition 中出色地描述了这个问题。查看 Google 图书搜索的相关部分

The advice he offers is to prefer lists to arrays. Your code might then look something like:

他提供的建议是更喜欢列表而不是数组。您的代码可能如下所示:

List<Stack<Card>> cards = new ArrayList<Stack<Card>>();

回答by Peter Lawrey

You can do the following, though this gives you a compiler "unchecked" warning.

您可以执行以下操作,尽管这会给您一个编译器“未经检查”的警告。

Stack<Card>[] cards = (Stack<Card>[]) new Stack[52];

回答by Peter Lawrey

Stack<Card>[] decks = new Stack[9];       // Declare
Card c = decks[5].pop();                  // This compiles - java 'knows' the type
Integer i = decks[4].pop();               // This will not compile

回答by ?ukasz Bownik

Why do you use arrays anyway ?

你为什么要使用数组?

It is a low level programming structure.

它是一种低级编程结构。

Using Listor Setinstead (eg org.apache.commons.collections.list.LazyList) if you don't want to bother with innitialization.

如果您不想打扰初始化,请使用ListorSet代替(例如org.apache.commons.collections.list.LazyList)。

Or at least

或者至少

Arrays.asList(new Stack[52])to wrap an array into a list.

Arrays.asList(new Stack[52])将数组包装到列表中。

I couldnt reproduce jour error anywany .. :( perchaps it's because a different warning/errorlevel set.

我无论如何都无法重现 jour 错误.. :( 可能是因为设置了不同的警告/错误级别。

回答by Cogsy

It's to do with type erasure. Basically the generic types only exist at compile time and have no presence at run time

这与类型擦除有关。基本上泛型类型只在编译时存在,在运行时不存在

Have at look at this forum postfor a better explanation.

看看这个论坛帖子以获得更好的解释。

回答by Norbert Hartl

Well, the array does not need to be a generic because he is always defined as this. Why do you think you have to cast? I think that eclipse is somewhat confused here.

好吧,数组不需要是泛型的,因为他总是这样定义的。为什么你认为你必须投?我认为 eclipse 在这里有些混乱。