toArray方法不在扩展ArrayList <>的类中工作

Hog*_*790 0 java arrays extends arraylist

我有一个名为"Table"的类,它扩展了ArrayList.在这个类中,我有一个名为toArray()的方法.每当我编译我得到错误:"表中的toArray()无法在java.util.List中实现toArray()返回类型void与java.lang.Object []不兼容

这是Table类:

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]);
    }
}
Run Code Online (Sandbox Code Playgroud)

}

任何建议将非常感谢!

Mar*_*nik 11

一般建议:不要从非客户端子类化的类扩展.ArrayList是这样一个类的一个例子.而是定义您自己的实现List接口的类,并包含ArrayList重用其功能的类.这是装饰者模式.

具体建议:toArray是一种定义的方法ArrayList,您不能使用不同的返回类型覆盖它.

  • 或者更好:扩展`AbstractList`(http://docs.oracle.com/javase/7/docs/api/java/util/AbstractList.html) (6认同)
  • 甚至更好:[`ForwardingList`](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/ForwardingList.html) (2认同)