Mazz
Mazz

Reputation: 257

add values to double[] arraylist

I have the following array

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

and I would like to add values like this

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

but in a loop like this

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

obviously this is adding a new array each time with the single value... so how do I get it to add all into one array?

Upvotes: 3

Views: 44043

Answers (4)

Bhesh Gurung
Bhesh Gurung

Reputation: 51030

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

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

Upvotes: 7

arnold
arnold

Reputation: 1

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("  ");
             }
         }
}

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

Upvotes: 0

Dave Newton
Dave Newton

Reputation: 160171

Create the double[] first, add the numbers to it, and add that array to the List.

(The variable should likely be declared as a List, btw, not an ArrayList, unless you're specifically passing it to something that explicitly expects an ArrayList.)

Upvotes: 1

NitroG42
NitroG42

Reputation: 5356

With something like that :

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);

Upvotes: 0

Related Questions