Array Confusion with Doubles/doubles
I have tw开发者_开发知识库o 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));
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);
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];
}
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);
}
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);
double[] both = (double[]) ArrayUtils.addAll(Arrayweight, Arraypulse);
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));
精彩评论