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

JoeCrayon :

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
ruohola :

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=35510&siteId=1