将 ArrayList 转换为 Array 抛出 java.lang.ArrayStoreException

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15120089/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 18:32:30  来源:igfitidea点击:

Convert ArrayList to Array throws java.lang.ArrayStoreException

javaarraysexceptionarraylistthrows

提问by Hoggie1790

i have a method convertToArray()which converts an ArrayListto an array. I want to call this method every time an element is added to the ArrayList.

我有一个convertToArray()将 an 转换ArrayList为数组的方法。每次将元素添加到ArrayList.

public class Table extends ArrayList<Row>
{
public String appArray[]; //Array of single applicant details
public String tableArray[][]; //Array of every applicant
/**
 * Constructor for objects of class Table
 */
public Table()
{
}

public void addApplicant(Row app)
{
    add(app);
    convertToArray();
}

public void convertToArray()
{
    int x = size();
    appArray=toArray(new String[x]);
}

}

}

When i call the addApplication(Row app)method I get the error: java.lang.ArrayStoreException

当我调用该addApplication(Row app)方法时,出现错误:java.lang.ArrayStoreException

So I changed my addApplicant()method to:

所以我改变了我的addApplicant()方法:

 public void addApplicant(Row app)
 {
    add(app);
    if (size() != 0)
    convertToArray();
}

I get the same error message. Any ideas why? I figured if it checks the ArrayListhas elements before converting it the error should not be thrown?

我收到相同的错误消息。任何想法为什么?我想如果它ArrayList在转换之前检查has 元素,不应该抛出错误?

I can provide the full error if needed

如果需要,我可以提供完整的错误

回答by Anton-M

ArrayStoreException thrown to indicate that an attempt has been made to store the wrong type of object into an array of objects.

抛出 ArrayStoreException 以指示已尝试将错误类型的对象存储到对象数组中。

So,

所以,

public Row[] appArray; // Row - because you extend ArrayList<Row>

public void convertToArray()
{
    int x = size();
    appArray = toArray(new Row[x]);
}