From array of primitives to Collection

Say that you are working with some Java code, and you have in your hands an array of doubles. For some reason, you need to access that data as a Collection. How could you do that?

If instead of a primitive type you had an array of objects the solution would have been pretty easy. In the Arrays utility class there is a method exactly tailored for this use, asList(), that creates a new ArrayList collection out of a passed array. But in this case you have to work a bit more.

Firstly, let's see how Arrays.asList() works:
String[] sa = { "one", "two", "three" };
Collection<String> sc = Arrays.asList(sa); // 1
System.out.println("Max is: " + Collections.max(sc)); // 2
1. As promised, it was very easy indeed.
2. And now we can use the utility methods!

It is a pity, but we can't do the same for an array of primitive values:
double[] da = { 1d, 2d, 3d };
Collection<Double> dl = Arrays.asList(da); // 1 !!! error !!!
1. Sadly we have a "Type mismatch: cannot convert from List<double[]> to List<Double>".

Here autoboxing (that useful feature available from Java 1.5 that automatically converts any primitive type to its matching wrapper type) is not working, and for a good reason: performance for huge array conversions. If you really need to box an array of primitives you have to do it explicitly.
Collection<Double> dl = new ArrayList<Double>(da.length);
for(double d : da)
Double max = Collections.max(dl);
System.out.println("Max is: " + max);

No comments:

Post a Comment