As a class assignment, I have to implement a custom implementation of AbstractCollection, and to make use of generics. I found out that AbstractCollection.toArray()
hides its default T
type as follows:
public <T> T[] toArray(T[] a) { ... }
I initially thought the following would work, but I'm being told by my IDE that it won't override the super:
@Override
public T[] toArray(T[] a) { ... }
So, then I add <T>
to the method signature, and now (although it will compile) am being told the following:
Array of type 'T[]' expected
//Reports two types of suspicious calls to Collection.toArray().
//The first type is any calls where the type of the specified array argument
// is not of the same type as the array type to which the result is casted.
//Example:
void m(List list) {
Number[] ns = (Number[])
list.toArray(new String[list.size()]);
}
//The second type is any calls where the type of the specified array argument doesn't match
// the type parameter of the collection declaration.
//Example:
void m(List<Number> list) {
Number[] ns =
list.toArray(new String[list.size()]);
}
So, my first question is, is there a good reason why it's done this way to begin with? And secondly, will this affect my implementation in any way?