1

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> ?

5

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.