0

I have this snippet :

static class Foo {
    Double[] array;
    Double value;

    public Foo(Double[] array) {
        this.array = array;
    }

    Foo(double value){
        this.value = value;
    }
}

public static void main(String[] args) {
    double[] array = new double[]{1,2,3,4,5,6,7};
    double value = 10;

    new Foo(value);   //this is normal
    new Foo(array);   //syntax error cannot resolve constructor Foo(double[])
}

I get syntax error

cannot resolve constructor 'Foo(double[])'

Why I can pass variable of type double to method that receive Double , but I cannot pass an array of type double[] to method that receive Double[] as parameter

Ali Faris
  • 17,754
  • 10
  • 45
  • 70
  • 2
    There is no autoboxing/unboxing for entire arrays. – user207421 Jan 27 '18 at 06:21
  • 3
    As mentioned in above comment, there is no auto boxing for array. YOu can find the same discussion in this thread https://stackoverflow.com/questions/45918075/why-autoboxing-doesnt-work-in-arrays – sayboras Jan 27 '18 at 06:21
  • https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html – DavidX Jan 27 '18 at 06:23

4 Answers4

4

Because double is primitive and Double is not. So when you assign a primitive vs Wrapper boxing/unboxing works. But there is no such mechanism for whole array.

And also double[] have no null's at all upon initialisation because they hold primitives where as Double[] can hold nulls and they can't be interchangeable and they are incompatible.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
2

In Java arrays are objects and created using new operator. Your method expects a Double[] type of object and you are passing double[] type of object.

You are expecting java should perform auto-boxing/unboxing, But that happen between primitive types and their wrapper classes not for array, as they are objects in themselves.

Reference: JLS: Arrays

YoungHobbit
  • 13,254
  • 9
  • 50
  • 73
1

Autoboxing only works for primitive types (double -> Double). double[] and Double[] are arrays, each with their different types, and Java will not box/unbox these automatically.

Caius Brindescu
  • 607
  • 4
  • 13
0

Like others have said, autoboxing doesn't work for arrays.

But in your example, you can initialize our double array this way.

Double[] array = new Double[]{1.0,2.0,3.0,4.0,5.0,6.0,7.0};
DavidX
  • 1,281
  • 11
  • 16