使用来自 T 类的方法扩展 ArrayList<T> [英] Use method from T class extending ArrayList&lt;T&gt;

查看:31
本文介绍了使用来自 T 类的方法扩展 ArrayList<T>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不确定标题是否有意义,我会尽力解释.我有一个扩展 ArrayList 的 CustomList,T 是让我们说 Class A1 和 Class A2,它们都扩展了 Class A,它是一个自定义 Class.

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.

我需要这样做:

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

方法getCustomBoolean()是一个Class A方法,这个CustomList只用于A1A2>,我确定 obj.getCustomBoolean() 不会导致异常.

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.

我需要一种方法来指定 T 是 A 的子类.

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

推荐答案

将班级的第一行更改为此.

Change the very first line of your class to this.

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

这指定 T 可以是任何类型,它是 A 的子类型.它将允许您在您的类代码中的 T 对象上使用 A 类型的方法.

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.

这篇关于使用来自 T 类的方法扩展 ArrayList<T>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆