Ali Faris
Ali Faris

Reputation: 18610

why I cannot pass double[] to Double[]

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

Upvotes: 0

Views: 241

Answers (4)

DavidX
DavidX

Reputation: 1319

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};

Upvotes: 0

YoungHobbit
YoungHobbit

Reputation: 13402

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

Upvotes: 2

Caius Brindescu
Caius Brindescu

Reputation: 617

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.

Upvotes: 1

Suresh Atta
Suresh Atta

Reputation: 122008

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.

Upvotes: 4

Related Questions