Trey Balut
Trey Balut

Reputation: 1395

Array Confusion with Doubles/doubles

I have two Arrays that are initialized as such:

    public static double[] arrayweight= new double[100];
    public static double[] arraypulse= new double[100];

They are filled with data e.g. 23.0,25.8....etc.

I need to combine the two Arrays into one array of double[]

I have chosen to use the following approach which does not work. Any ideas?

     ArrayList <Double> al = new ArrayList<Double>();

// The following methods do not work ;(     
     al.add((double[]) Global.arrayweight);
     al.add(new Double(Global.arraypulse));

Upvotes: 3

Views: 197

Answers (6)

Peter Lawrey
Peter Lawrey

Reputation: 533590

You might find TDoubleArrayList useful. This is a wrapper for double[].

TDoubleArrayList al = new TDoubleArrayList();
al.add(Arrayweight);
al.add(Arraypulse);

However your naming suggest you are using arrays when objects might be a better approach.

class MyData {
    double weight, pulse;
}

List<MyData> al = new ArrayList<MyData>();
for(int i=0;i<100;i++) {
    MyData md = new MyData();
    md.weight = ...
    md.pulse = ...
    al.add(md);
}

Upvotes: 1

Eng.Fouad
Eng.Fouad

Reputation: 117597

How about the easy way:

double[] arr = new double[Arrayweight.length + Arraypulse.length];
int counter = 0;
for(double d1 : Arrayweight) arr[counter++] = d1;
for(double d2 : Arraypulse)  arr[counter++] = d2;

or (if they have same length):

int length = Arrayweight.length + Arraypulse.length;
double[] arr = new double[length];
for(int i = 0; i < length / 2; i++)
{
    arr[i] = Arrayweight[i];
    arr[i + length / 2] = Arraypulse[i];
}

Upvotes: 2

Ray Toal
Ray Toal

Reputation: 88398

I like Nammari's answer best, but just in case you are not using Commons Lang and want to stick with pure Java:

double[] result = Arrays.copyOf(Arrayweight, Arrayweight.length + Arraypulse.length);
System.arrayCopy(Arraypulse, 0, result, Arrayweight.length, Arraypulse.length);

Upvotes: 0

Mahesh
Mahesh

Reputation: 34625

You can achieve it using System.arraycopy.

double[] cArray= new double[Arrayweight.length + Arraypulse.length];
System.arraycopy(Arrayweight, 0, cArray, 0, Arrayweight.length);
System.arraycopy(Arraypulse, 0, cArray, Arrayweight.length, Arraypulse.length);

Upvotes: 3

Klarth
Klarth

Reputation: 2045

The add method takes individual values, not arrays. You can combine List's addAll and Arrays' asList method (if you want to stick with an ArrayList):

al.addAll(Arrays.asList(Global.Arrayweight));
al.addAll(Arrays.asList(Global.Arraypulse));

Upvotes: -1

confucius
confucius

Reputation: 13327

double[] both = (double[]) ArrayUtils.addAll(Arrayweight, Arraypulse);

Upvotes: 0

Related Questions