Java - Is new Stack<?>[N] equivalent to new

2019-05-07 07:41发布

Is new Stack<?>[N] equivalent to new Stack[N] for a generic data type Stack<Item>?

EDIT: While I understand that mixing generic types and arrays should best be avoided and that more robust solutions exist, my query still stands: widely recognized textbooks such as Algorithms, 4th Edition by Kevin Wayne and Robert Sedgewick (pg. 158) suggest using constructs like the following:

Stack<String>[] a = (Stack<String>[]) new Stack[N];

2条回答
看我几分像从前
2楼-- · 2019-05-07 07:51

[ Turning my comment into a real answer ]

1) Mixing arrays and generic types should be avoided.

2) Instead, one can use Java Collection types, for example ArrayList when the need comes up to handle multiple "generic" objects, like in

ArrayList<Stack<String>> theStacks = new ArrayList<>();
查看更多
时光不老,我们不散
3楼-- · 2019-05-07 07:54

Yes, they are equivalent, except for the return type (one is Stack[], the other is Stack<?>[]).

Note that Stack[] can be assigned to Stack<String>[] without an explicit cast (you will just get an unchecked conversion warning), whereas it is an error to assign a Stack<?>[] to Stack<String>[] without a cast.

new Stack[N] uses a raw type which is not recommended in new code.

查看更多
登录 后发表回答