0

我有一个 ArrayList Stringint其中double包含 20 个元素。

我试图将 移至Strings字符串数组、ints移至 int 数组和doubles移至双数组。但我不知道如何,这就是我寻找整数的方法:

    private ArrayList <Object> randomList = new ArrayList <Object>();
    private int [] intArray = new int[10];

    public void example(){
    createArray();
    for(int i = 0; i<randomList.size();i++){
        if(randomList.get(i)instanceof Integer){
            intArray[i]= (Integer) randomList.get(i);
        }
    }
}

我不明白为什么这个 dosnt 起作用,它试图将不是整数的对象添加到我的数组中,导致 outOfBounds 异常,因为它试图添加超过 10 个元素。

4

5 回答 5

2

您有索引不匹配,仅此而已。尝试类似:

int index = 0;

for(int i = 0; i<randomList.size();i++)
{
        if(randomList.get(i)instanceof Integer)
        {
            intArray[index++]= (Integer) randomList.get(i);
        }
}

您还应该检查特定数组的当前索引是否小于上限,即该数组的初始大小:

if(randomList.get(i) instanceof Integer && index < intArray.length)
于 2012-11-26T19:59:46.737 回答
0

您需要为每个输出数组维护一个单独的索引。

于 2012-11-26T19:59:54.633 回答
0

Well first of all you should never have allowed all these data types to congregate in on ArrayList of objects. But if you already have them:

for(Object o : randomList)
{
    if(o instanceof Integer)
    {
        //add to inteeger list
    }
    else if(o intenaceof String)
    {
       //add to string list
    }
    //...etc
}
于 2012-11-26T20:00:18.640 回答
0
  1. Try initializing your array as :

    private int [] intArray = new int[randomList.size()];
    
  2. Try another index to assign values to array:

    int count=0;
    for(int i = 0; i<randomList.size();i++){
        if(randomList.get(i)instanceof Integer){
           intArray[count++] = (Integer) randomList.get(i);
        }
    }        
    
  3. In the end, you may want to truncate the array fragment which was unused using System.arraycopy as below:

    private int [] finalArray= new int[count;
    System.arraycopy(intArray, 0, finalArray, 0, count);
    
于 2012-11-26T20:00:33.433 回答
0
private int [] intArray = new int[10];

Your array has a size of 10, but your list does not have a size limit.

private int [] intArray = new int[randomList.size()];

might work.

于 2012-11-26T20:01:02.460 回答