javaarraysarraylistcollectionstoarray

toArray() returns object[]


I am trying to convert an ArrayList to an Array using toArray(), but it returns an object[] instead of double[]. See below:

double [] arr = arrList.toArray(new Double[arrList.size()]);

I'm getting an Incompatible Types error.

This is what the arrList contains:

I/System.out: [0.0, 2.455430030822754, 1.834529995918274, 0.7368429899215698, -0.5264459848403931, -1.5101100206375122, -1.8526500463485718, -1.6131700277328491, -0.9388419985771179, 0.053711701184511185, 0.35541099309921265, -0.18560799956321716, -0.884518027305603, -1.4304900169372559, -1.5486400127410889, -0.943471014499, 0.0]

This is how it is obtained:

private void rec(SensorEvent event) {

    double x = event.values[0];

    arrList.add(x);

}

I've tried without sizing the array (i.e. using new Double[0]) although I didn't think it would be the problem but that did not work either.

I looked for similar Qs online and all I found was on String examples, and I'm thinking Double might be the problem? Not too sure.

Quite new at this so apologies if obvious.


Solution

  • double [] arr = arrList.toArray(new Double[arrList.size()]);
    

    double[] is a different type than Double[]. While Java can convert between double and Double with autoboxing and autounboxing, it cannot convert from Double[] to double[]. You can fix the problem with:

    Double [] arr = arrList.toArray(new Double[arrList.size()]);