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.

1

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

4 Comments

Diamond operator <> was introduced in Java 7 but OP states that he is using Java 6
Your features is empty. Not really and filling that array is not necessary for this example. (repost due to evil typo)
@Tom Or it would be 19 null(s).
:D right, you had to fix the type to correct the code, already forgot that. But "his" features isn't empty :P.
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.

1 Comment

I observed that it didn't compile with new ArrayList<Double>(Arrays.asList(features)) but failed to understand what the problem was. Thanks for pointing it out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.