我有一个名为“Table”的类,它扩展了 ArrayList。在这个类中,我有一个名为 toArray() 的方法。每当我编译时,我都会收到错误:“Table 中的 toArray() 无法实现 java.util.List 中的 toArray() 返回类型 void 与 java.lang.Object[] 不兼容”
这是表类:
public class Table extends ArrayList<Row>
{
public ArrayList<String> applicants;
public String appArray[];
public String appArray2[] = {"hello", "world","hello","world","test"};
/**
* Constructor for objects of class Table
*/
public Table()
{
applicants = new ArrayList<String>();
}
public void addApplicant(String app)
{
applicants.add(app);
toArray();
}
public void toArray()
{
int x = applicants.size();
if (x == 0){ } else{
appArray=applicants.toArray(new String[x]);}
}
public void list() //Lists the arrayList
{
for (int i = 0; i<applicants.size(); i++)
{
System.out.println(applicants.get(i));
}
}
public void listArray() //Lists the Array[]
{
for(int i = 0; i<appArray.length; i++)
{
System.out.println(appArray[i]);
}
}
}
如有任何建议,我们将不胜感激!
最佳答案
一般建议:不要从不适合客户端子类化的类进行扩展。 ArrayList
就是此类的一个示例。相反,定义您自己的类来实现 List
接口(interface)并包含 ArrayList
来重用其功能。这就是装饰器模式。
具体建议:toArray
是 ArrayList
中定义的方法,您不能使用不同的返回类型覆盖它。
关于java - toArray 方法在扩展 ArrayList<> 的类中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15025313/