将 ArrayList 转换为 Array 抛出 java.lang.ArrayStoreException [英] Convert ArrayList to Array throws java.lang.ArrayStoreException

查看:15
本文介绍了将 ArrayList 转换为 Array 抛出 java.lang.ArrayStoreException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方法 convertToArray()ArrayList 转换为数组.每次将元素添加到 ArrayList 时,我都想调用此方法.

i have a method convertToArray() which converts an ArrayList to an array. I want to call this method every time an element is added to the 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]);
}

}

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

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

所以我将我的 addApplicant() 方法更改为:

So I changed my addApplicant() method to:

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

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

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

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

I can provide the full error if needed

推荐答案

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

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

所以,

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

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

这篇关于将 ArrayList 转换为 Array 抛出 java.lang.ArrayStoreException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆