This will compile:
@SuppressWarnings("unchecked") // this is okay because [insert reasoning here]
private LinkedListDemo<S, T>[] table =
(LinkedListDemo<S, T>[]) new LinkedListDemo<?, ?>[10];
The reason your code errors is because an Object[]
is not a LinkedListDemo[]
, similarly to how an Object
is not a LinkedListDemo
.
The earlier unchecked casts work because S[]
and T[]
have been erased to Object[]
at runtime.
In general, arrays of parameterized types are discouraged because their very existence is unsafe. This is because:
- Arrays are covariant - a
LinkedListDemo<S, T>[]
is anObject[]
. So one could assigntable
to anObject[]
variable and then assign aString
as an element - this would be legal at compile time but would at least fail at runtime with anArrayStoreException
, since arrays do runtime type checking. - Generic type information is not available at runtime because it's been erased by the compiler. One could once again assign
table
to anObject[]
variable but this time assign aLinkedListDemo<String, Integer>
as an element. At runtime, the array would only see that a plainLinkedListDemo
had been added, so it would not fail right away if the generic types were wrong. This might lead to unexpectedClassCastException
s at some later time.
See my answer here for a fuller explanation and example of this issue. See also this great explanation by Angelika Langer's Generics FAQ: Can I create an array whose component type is a concrete parameterized type?
The takeaway is that it will be much easier and safer to simply use a List<LinkedListDemo<S, T>>
instead. If you ultimately decide to stick to using LinkedListDemo<S, T>[]
, make sure that it is carefully hidden as an implementation detail and stay cognizant about how it can be misused.
A couple of other misc notes:
@SuppressWarnings("unchecked")
doesn't do anything but suppress the unchecked cast compiler warning. It's essentially saying "trust me I know what I'm doing" - but you still need to be careful that an unchecked cast isn't being misused. See this post for more info: How do I address unchecked cast warnings?- Like all core API classes, the source for
HashMap
is available so you should feel free to look over it if you want to understand its inner workings better.