如何正确实现java.util.Collection类?

问题描述 投票:1回答:1

我想编写自己的Linked-list <T>并实现java.util.Collection <T>。

我的问题是警告:“类型参数T隐藏类型T”。当我重写方法public <T> T[] toArray(T[] arg0){}时发生

这是我的代码:

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 
    ...
}

(我知道我可以扩展AbstractCollection类,但这不是我想要做的)。

任何人都知道如何解决这个问题? 我应该将Collection <T>中的参数T更改为其他类似的字母:Collection< E>

java eclipse collections
1个回答
2
投票

你得到这个错误,因为方法<T> T[] toArray(T[] arg0)采用了它自己的泛型参数,它独立于你的类的泛型参数T

如果你需要在T实现中提供T(类的)和toArray(方法的)类型,你需要重命名这些类型之一。例如,Java引用实现使用E(用于“element”)作为集合类的泛型类型参数:

public class MyLinkedList<E>  implements Serializable, Iterable<E>, Collection<E>
{
    //some constructor here.  

    public <T> T[] toArray(T[] arg0)
    {
        return null;
    }
    ...
    // all other methods 
    ...
}

现在两个通用参数的名称不同,这解决了问题。

© www.soinside.com 2019 - 2024. All rights reserved.