Arrays.asList().contains() on Double vs double arrays

I have a double array doubleArray1. I tried a Arrays.asList().contains() operation as shown below

double doubleArray1 [] = {1D,2D,3D};
if(Arrays.asList(doubleArray1).contains(1D)) {
    System.out.println("hello-1");
}

It does not print anything. Then I made it a Double array

Double doubleArray1 [] = {1D,2D,3D};        
if(Arrays.asList(doubleArray1).contains(1D)) {
    System.out.println("hello-1");
}

It prints hello-1.

Could someone explain why this difference?

Jon Skeet
people
quotationmark

Your first call to Arrays.asList is actually returning a List<double[]> - it's autoboxing the argument, because a double[] isn't a T[]... generics don't allow for primitive types as type arguments.

If you want to convert a double[] into a List<Double>, you either need to do it manually or use a third-party library to do it. For example:

public List<Double> toList(double[] doubles) {
    List<Double> list = new ArrayList<>(doubles.length);
    for (double x : doubles) {
        list.add(x);
    }
    return list;
}

Note that unlike Arrays.asList any subsequent changes to the array will not be reflected in the list or vice versa - it's a copy, not a view.

people

See more on this question at Stackoverflow