Reputation: 127
I want to write my own Linked-list< T> and implement java.util.Collection< T>.
My problem is the warning: "The type parameter T is hiding the type T". that occures when I override the method public <T> T[] toArray(T[] arg0){}
Here's my code:
public class MyLinkedList<T> implements Serializable,Iterable<T>, Collection<T>
{
//some constructor here.
public <T> T[] toArray(T[] arg0) // I get that error here under the <T> declaration
{
return null;
}
...
// all other methods
...
}
(I know I can extend AbstractCollection class instead but that's not what I want to do).
Anybody have any idea how to solve this?
Should I change the parameter T in Collection< T> to be some other letter like so: Collection< E>
?
Upvotes: 1
Views: 245
Reputation: 727137
You get this error because method <T> T[] toArray(T[] arg0)
takes a generic parameter of its own, which is independent of the generic parameter T
of your class.
If you need both types T
(of the class) and T
(of the method) to be available inside toArray
implementation, you need to rename one of these types. For example, Java reference implementations use E
(for "element") as the generic type argument of collection classes:
public class MyLinkedList<E> implements Serializable, Iterable<E>, Collection<E>
{
//some constructor here.
public <T> T[] toArray(T[] arg0)
{
return null;
}
...
// all other methods
...
}
Now the names of the two generic parameters are different, which fixes the problem.
Upvotes: 2