-1

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?

4J41
  • 5,005
  • 1
  • 29
  • 41

3 Answers3

8

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0

Generic allows to use class type not primitive type. Hence while comparing this with primitive it does not give you the desire out put but class type gives you the result.

Qadir Hussain
  • 1,263
  • 1
  • 10
  • 26
0

To add to Jon's answer: asList takes a vararg (variable arity) parameter list, and vararg parameters don't autobox the way one might expect. A simple case that doesn't involve generics:

public void foo(Double... x) { whatever }

double[] doubleArray1 = {1D,2D,3D};

foo(doubleArray1);  // error

gives the error argument type double[] does not conform to vararg element type Double. The same applies to asList; what happens here is that since Arrays.asList is generic and you haven't explicitly given it the generic type, it will pick whatever works; Double doesn't work (for the same reasons the foo call won't compile), and double[] does work. This expression, where you explicitly give it the generic parameter, will give you the same error at compile time:

Arrays.<Double>asList(doubleArray1).contains(1D)
ajb
  • 31,309
  • 3
  • 58
  • 84