为double [] arraylist添加值

时间:2011-10-26 15:07:14

标签: java arrays arraylist

我有以下数组

ArrayList<double[]> db_results = new ArrayList<double[]>(); 

我想添加像这样的值

db_results.add(new double[] {0,1,2});

但是像这样的循环

for ( int i = 0 ; i <= 2; i++) {
    double val = Double.parseDouble(i);
    db_results.add(new double[] {val});
}

显然这是每次使用单个值添加一个新数组...所以如何将它添加到一个数组中呢?

4 个答案:

答案 0 :(得分:6)

double[] nums = new double[3];
for ( int i = 0 ; i <= 2; i++) {
    double val = Double.parseDouble(i);
    nums[i] = val;        
}
db_results.add(nums);

答案 1 :(得分:1)

首先创建double[],向其中添加数字,然后将该数组添加到List

(该变量应该被声明为List,顺便说一句,而不是ArrayList,除非你专门将它传递给明确要求ArrayList的东西。)

答案 2 :(得分:0)

有类似的东西:

max = 3;
double[] doubles = new double[max];
for ( int i = 0 ; i < max; ++i)
    {
     double val = Double.parseDouble(i);
     doubles[i] = val;
    }
db_results.add(doubles);

答案 3 :(得分:0)

import java.util.Scanner;
class DarrayEx2
{
    public static void main(String args[])
      {
       int a[][]=new int[3][3];
       int r,c,sumr;
       Scanner s=new Scanner(System.in);
        for(r=0;r<a.length;r++)
         {
           for (c=0;c<a.length ;c++ )
            {
             System.out.println("enter an  element");
             a[r][c]=s.nextInt();
            }
          }
          for(r=0;r<a.length;r++)
            {
              sumr=0;
              System.out.println("elements in a["+r+"] row is");
               for (c=0;c<a[1].length ;c++ )
                 {
                   System.out.println(" "+a[r][c]);
                   sumr = sumr+a[r][c];
                 }

               System.out.println(" = "+sumr);
               System.out.println("  ");
             }
         }
}

来源:http://www.exceptionhandle.com/portal/java/core-java/part-12-arrays.htm