[英]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.