Multiple restrictions on generic type based on super and sub classes in java

淺唱寂寞╮ 提交于 2020-01-23 08:29:47

问题


I have a generic list class that implements a particular interface.

The list items in the interface also implement the same interface.

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

    ...
}

So now I want to make a subclass of this list that stays generic but limits the items to objects that implement the SearchListItem interface:

public interface SearchListItem
{
    public String getName();
}

Here's what I have for the SearchList class so far:

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

    ...
}

But of course this complains on the definition of the class:

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

So what do I need to put into the class declaration to say "SearchList extends the List class and has additional restrictions on the generic class type that includes both SomeInterface (in the base class) and SearchListItem as well"?

Please tell me if I can reword this to help explain it.


回答1:


Does this work?

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


来源:https://stackoverflow.com/questions/4085557/multiple-restrictions-on-generic-type-based-on-super-and-sub-classes-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!