3

This post shows that the code below creates a List from an array.

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

I'm expecting list to contain 19 elements, each of which is 0.0. However, after running the code above, list only contains 1 element, which is [0.0, 0.0, ..., 0.0]. I'm running Java 6 and not sure if this is related.

Community
  • 1
  • 1
goldfrapp04
  • 2,326
  • 7
  • 34
  • 46

2 Answers2

2

Don't use Raw Types. Your features is empty. And you can't make a collection of a 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);
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
2

Every array is also an object. You call to Arrays.asList creates a List with a single element, which is the entire array. So you are creating a List<double[]>, not a List<Double>. Since you were using a raw type, the compiler did not spot this error and compiled with only a warning message. If you would have typed new ArrayList<Double>(Arrays.asList(features)), your program would not have compiled.

Hoopje
  • 12,677
  • 8
  • 34
  • 50
  • I observed that it didn't compile with `new ArrayList(Arrays.asList(features))` but failed to understand what the problem was. Thanks for pointing it out. – goldfrapp04 Nov 15 '14 at 21:41