Using Arrays.asList to create a list from an array

This post shows what the code below creates List

from an array.

double[] features = new double[19];
List<Double> list = new ArrayList(Arrays.asList(features));

      

I expect it List

will contain 19 elements, each of which is 0.0. However, after executing the above code, it List

contains only one element which is equal to [0.0, 0.0, ..., 0.0]

. I am running Java 6 and am not sure if this is related.

+3


source to share


2 answers


Don't use Raw types . Yours is features

empty. And you cannot create a collection of the primitive type double

you need double

.



Double[] features = new Double[19]; // <-- an Object type
Arrays.fill(features, Double.valueOf(1)); // <-- fill the array
List<Double> list = new ArrayList<Double>(Arrays.asList(features));
System.out.println(list);

      

+2


source


Each array is also an object. You call Arrays.asList

creates a list with one element, which is an integer array. Thus, you are creating List<double[]>

, not List<Double>

. Since you were using a raw type, the compiler did not catch this error and only compiled with a warning message. If you had typed new ArrayList<Double>(Arrays.asList(features))

, your program would not have been compiled.



+2


source







All Articles