Reputation: 191
Since generics are invariant. The following code produces a compile time error incompatible types
:
Stack<String> stackOfStrings = new Stack<String>();
Stack<Object> stackOfObjects = stackOfStrings;
Why then is the code below that produces an array of a stack of strings acceptable to the compiler and taught in textbooks such as Algorithms, 4th Edition by Robert Sedgwick and Kevin Wayne, pg. 158:
Stack<String>[] a = (Stack<String>) Stack[];
EDIT: the above snippet taken directly from the textbook is actually (sorry for the mistake):
Stack<String>[] a = (Stack<String>[]) new Stack[N];
Upvotes: 0
Views: 105
Reputation: 122489
It is unclear what you are asking. You say that the first thing doesn't work and the second does, but make not obvious connection between the two.
Generics are invariant, meaning that Foo<A>
and Foo<B>
are not subtypes of one another, if A
and B
are different concrete types, even if there is a sub typing relationship between A
and B
.
I don't see that situation happening in the second example. It is possible to convert between the raw type Foo
and Foo<A>
. That's not converting from one parameter to another as in the first example.
Upvotes: 1
Reputation: 926
First issue: to solve this you could use
Stack<? extends Object> stackOfObjects = stackOfStrings;
. You have to tell the compiler subtypes are also allowed in the generic class.
Second: My compiler isn't allowing it.
Upvotes: 3