【问题标题】:Multiple restrictions on generic type based on super and sub classes in javajava中基于超类和子类对泛型类型的多重限制
【发布时间】:2011-05-04 09:19:09
【问题描述】:

我有一个实现特定接口的通用列表类。

接口中的列表项也实现了相同的接口。

public abstract class List<T extends SomeInterface> implements SomeInterface
{
    protected LinkedList<T> m_list;

    ...
}

所以现在我想创建这个列表的子类,它保持通用但将项目限制为实现 SearchListItem 接口的对象:

public interface SearchListItem
{
    public String getName();
}

到目前为止,我对 SearchList 类的内容如下:

public abstract class SearchList<T extends SearchListItem> extends List<T>
{
    public T get(String name)
    {
        ...
    }

    ...
}

但这当然抱怨类的定义:

Bound mismatch: The type T is not a valid substitute for the bounded parameter <T extends SomeInterface> of the type List<T>

那么我需要在类声明中添加什么来说明“SearchList 扩展了 List 类并且对包括 SomeInterface(在基类中)和 SearchListItem 的泛型类类型有额外的限制”?

请告诉我是否可以改写它以帮助解释它。

【问题讨论】:

    标签: java inheritance interface generics subclass


    【解决方案1】:

    这行得通吗?

    public abstract class SearchList<T extends SomeInterface & SearchListItem> extends List<T>
    

    【讨论】:

    • 完美!我已经实现了它,它的声音。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-02
    • 1970-01-01
    • 2018-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多