Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this int array not passed as an object vararg array?

Tags:

java

I used this code. I am confused why this int array is not converted to an object vararg argument:

class MyClass {
    static void print(Object... obj) {
        System.out.println("Object…: " + obj[0]);
    }

    public static void main(String[] args) {
        int[] array = new int[] {9, 1, 1};
        print(array);
        System.out.println(array instanceof Object);
    }
}

I expected the output:

Object…: 9
true

but it gives:

Object…: [I@140e19d
true
like image 533
JoeCrayon Avatar asked May 11 '19 17:05

JoeCrayon


3 Answers

You're running into an edge case where objects and primitives don't work as expected. The problem is that the actual code ends up expecting static void print(Object[]), but int[] cannot be cast to Object[]. However it can be cast to Object, resulting in the following executed code: print(new int[][]{array}).

You get the behavior you expect by using an object-based array like Integer[] instead of int[].

like image 160
Kiskae Avatar answered Oct 14 '22 10:10

Kiskae


The reason for this is that an int array cannot be casted to an Object array implicitly. So you actually end up passing the int array as the first element of the Object array.

You could get the expected output without changing your main method and without changing the parameters if you do it like this:

static void print(Object... obj) {
    System.out.println("Object…: " + ((int[]) obj[0])[0]);
}

Output:

Object…: 9
true
like image 45
ruohola Avatar answered Oct 14 '22 09:10

ruohola


As you know, when we use varargs, we can pass one or more arguments separating by comma. In fact it is a simplification of array and the Java compiler considers it as an array of specified type.

Oracle documentation told us that an array of objects or primitives is an object too:

In the Java programming language, arrays are objects (§4.3.1), are dynamically created, and may be assigned to variables of type Object (§4.3.2). All methods of class Object may be invoked on an array.

So when you pass an int[] to the print(Object... obj) method, you are passing an object as the first element of varargs, then System.out.println("Object…: " + obj[0]); prints its reference address (default toString() method of an object).

like image 36
aminography Avatar answered Oct 14 '22 11:10

aminography