2

First off, I want to say that I know this has been asked before at the following location (among others), but I have not had any success with the answers there:

Create ArrayList from array

What I am trying to do is the following:

double[] FFTMagnitudeArray = processAudio.processFFT(audioData);


List<Double> FFTMagnitudeList = Arrays.asList(FFTMagnitudeArray);


audioData.setProperty("FFTMagnitudeList", FFTMagnitudeList);

However, I get the error:

"Type mismatch: cannot convert from List<double[]> to List<Double>"

This makes no sense to me, as I thought the List was necessary and the Array.asList(double[]) would return a list of Double, not double[]. I have also tried the following, to no avail:

List<Double> FFTMagnitudeList = new ArrayList<Double>();
FFTMagnitudeList.addAll(Arrays.asList(FFTMagnitudeArray));


List<Double> FFTMagnitudeList = new ArrayList<Double>(Arrays.asList(FFTMagnitudeArray));

And I keep getting the same error.

So how do I create the List?

Community
  • 1
  • 1
Adrogans
  • 53
  • 10

3 Answers3

5

The double type is a primitive type and not an object. Arrays.asList expects an array of objects. When you pass the array of double elements to the method, and since arrays are considered as objects, the method would read the argument as an array of the double[] object type.

You can have the array element set the Double wrapper type.

Double[] FFTMagnitudeArray = processAudio.processFFT(audioData);
M A
  • 71,713
  • 13
  • 134
  • 174
5

Change your method to return the object wrapper array type.

Double[] FFTMagnitudeArray = processAudio.processFFT(audioData);
List<Double> FFTMagnitudeList = Arrays.asList(FFTMagnitudeArray);

Or you'll have to manually copy from the primitive to the wrapper type (for the List).

double[] FFTMagnitudeArray = processAudio.processFFT(audioData);
List<Double> FFTMagnitudeList = new ArrayList<>(FFTMagnitudeArray.length);
for (double val : FFTMagnitudeArray) {
  FFTMagnitudeList.add(val);
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
1

Using Java 8:

List<Double> FFTMagnitudeList = Arrays.stream(FFTMagnitudeArray).mapToObj(Double::valueOf).collect(Collectors.toCollection(ArrayList::new));

This creates a DoubleStream (a stream of the primitive type double) out of the array, uses a mapping which converts each double to Double (using Double.valueOf()), and then collects the resulting stream of Double into an ArrayList.

ajb
  • 31,309
  • 3
  • 58
  • 84