【问题标题】:toArray method not working in class that extends ArrayList<>toArray 方法在扩展 ArrayList<> 的类中不起作用
【发布时间】:2013-02-08 03:18:24
【问题描述】:

我有一个名为“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]);
    }
}

}

任何建议将不胜感激!

【问题讨论】:

  • 首先,开始改成if (x != 0) appArray=applicants.toArray(new String[x]);

标签: java arrays arraylist extends


【解决方案1】:

我不知道你想要完成什么,但你的方法应该是这样的。

@Override
public Object[] toArray(){
      return applicants.toArray();
   }
}

【讨论】:

    【解决方案2】:

    这是因为Collection 实现的ArrayList 已经声明了toArray() 方法。该方法返回Object[],这与您方法的返回类型void 不同,因此它不能用作覆盖。

    您的方法似乎在做一些完全不同的事情,所以最好的解决方案是重命名它。

    【讨论】:

      【解决方案3】:

      您正在重载一个名为 toArray 的方法。

      尝试调用其他名称,例如 convertToMyArray()

      【讨论】:

        【解决方案4】:

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

        具体建议:toArray 是在ArrayList 中定义的方法,您不能用不同的返回类型覆盖它。

        【讨论】:

        猜你喜欢
        • 2012-07-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-06-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-05
        相关资源
        最近更新 更多