Use method from T class extending ArrayList<T>

痞子三分冷 提交于 2019-12-12 14:13:11

问题


Not sure if the title makes sense, I will try to explain. I have a CustomList extending ArrayList, T being let's say Class A1 and Class A2, both extending Class A which is a custom Class.

I need to do this :

public class CustomList<T> extends ArrayList<T>
{
    public CustomList()
    {
        super();
    }

    public boolean add(T obj)
    {
        /*The method getCustomBoolean() is not defined for the type T*/
        if(obj.getCustomBoolean())
        {
            super.add(obj);
        }

        return true;
    }
}

The method getCustomBoolean() is a Class A method, and using this CustomList only for A1 and A2, I'm sure obj.getCustomBoolean() won't cause an exception.

I need a way to specify that T is a child class of A.


回答1:


Change the very first line of your class to this.

public class CustomList<T extends A> extends ArrayList<T>

That specifies that T can be any type which is a subtype of A. It will allow you to use methods of type A on your T object, within your class's code.




回答2:


Do it this way:

class A
{
    public boolean getCustomBoolean() {
        return false;
    }
}

class CustomList<T extends A> extends ArrayList<T>
{
    private static final long serialVersionUID = 1L;

    public CustomList()
    {
        super();
    }

    public boolean add(T obj)
    {
        if(obj.getCustomBoolean())
        {
            super.add(obj);
        }

        return true;
    }
}



回答3:


If you will be only using this CustomList with subclasses of A, than you can declare the CustomList class as:

public class CustomList<T extends ClassA> extends ArrayList<T>

But if not, than you have to rethink your design.




回答4:


Use:

class CustomList<T extends A> extends ArrayList<A>



回答5:


This works fine:

class A {
    public boolean getCustomBoolean () {
        return true;
    }
};
class A1 extends A {};
class A2 extends A {};

class CustomList<T extends A> extends ArrayList<A> {
    public boolean add (T obj) {
        if ( obj.getCustomBoolean() ) {
            super.add(obj);
        }
        return true;
    }
}

Note that if you extend ArrayList<A> you can add items of type A1 or A2 but if you extend ArrayList<T> you will be restricted to the type in the declaration.

    CustomList<A1> a1 = new CustomList<>();
    CustomList<A2> a2 = new CustomList<>();
    // Fine.
    a1.add(new A1());
    // Fine if you extend ArrayList<A> - not allowed if you extend ArrayList<T>.
    a2.add(new A1());


来源:https://stackoverflow.com/questions/23239393/use-method-from-t-class-extending-arraylistt

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