Arraylist到整数数组,无法让它工作(java)!

时间:2012-02-16 05:23:28

标签: java arrays arraylist

我正在创建一种方法来获取数组中所有偶数的平均值。

如何将arraylist对象(evens)转换为数组,以便总结它们?

    public static double percentEven(int[]a)
    {
    ArrayList evens = new ArrayList();
    int evenSum = 0;


    for (int counter = 0;counter < a.length;counter++)
    {
        if ((a[counter]%2) == 0 )    
        evens.add(a[counter]);
    }    

    int[] evenReturned = new int[evens.size()];
    evens.toArray(evenReturned);

    int evensCount = 0;
    for (evensCount = 0;evensCount < evens.size();evensCount++)
    {
        evenSum += evenReturned[evensCount];   
    }    


    return evenSum/evensCount;

  }    

4 个答案:

答案 0 :(得分:7)

你为什么要收集它们?总结一下吧!

int evensCount = 0;
int evenSum = 0;
for (int counter = 0; counter < a.length; counter++) {
    if (a[counter] % 2 == 0) {
        evensCount++;
        evenSum += a[counter];
    }
}

return evenSum/evensCount;

答案 1 :(得分:2)

虽然你不需要在这里做,但要将ArrayList转换为Arrays,请执行以下操作:

List<T> list = new ArrayList<T>();
T [] yourArray = list.toArray(new T[list.size()]);

答案 2 :(得分:1)

如果你想总结它们,那么只需使用专门的for循环来遍历evens ArrayList中的每个元素,例如

for (int e : evens)
{
   evenSum += e;
}

return evenSum/evensCount;

答案 3 :(得分:1)

你只需要这样做

if ((a[counter]%2) == 0 ) { 
    evenCount++ ;
    evens.add(a[counter]); // required only if you want an array of even numbers 
    evenSum += a[counter] ;
}
...
...
return evenSum / evenCount ;