简体   繁体   English

在泛型类中为数组列表实现Add方法

[英]Implementing an Add method for an Array List in a generic class

I keep getting an error telling me that add(T) is undefined for the type T when trying to add add : 尝试添加add时,我不断收到错误消息,告诉我类型T add(T)未定义:

package p07;
import java.util.ArrayList;

public class MyList<T extends Number>
{
    private T ArrayList;

    public MyList(T ArrayList)
    {
        this.ArrayList=ArrayList;
    }
    public void add(T x)
    {
        ArrayList.add(x);
    }
}

Any advice on how to proceed? 关于如何进行的任何建议?

You've incorrectly made the ArrayList a variable of type T . 您错误地使ArrayList成为T类型的变量。 The line private T ArrayList; 该行private T ArrayList; should be private ArrayList<T> l; 应该是private ArrayList<T> l; where l would be the variable name. 其中l是变量名。

The issue is that ArrayList is a generic type, so when you pass your generic type to it, you must pass it through ArrayList<T> . 问题在于ArrayList是泛型类型,因此当您将泛型类型传递给它时,必须通过ArrayList<T>传递它。 T ArrayList is a variable called ArrayList of type T . T ArrayList是类型为T名为ArrayList的变量。

You have to change this everywhere: every T you've shown in this snippet should be an ArrayList<T> . 您必须在各处进行更改:在此代码段中显示的每个T应该是一个ArrayList<T>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM