Sleiman Jneidi
Sleiman Jneidi

Reputation: 23349

why arrays of primitive types are not considered as objects

I know that arrays in java extends Objects,So why passing them as params doesn't work.

public static void main(String[] args) {
    foo(new Integer[]{1, 2, 3}); // 1
    foo(new int[]{1,2,3});   //2
}

static void foo(Object... params) {
    System.out.println(params[0]);
}

moreover,why it doesn't treat the array as a single parameter (line 1)

Output from running the above is:

1
[I@3e25a5

Upvotes: 3

Views: 814

Answers (3)

Etienne de Martel
Etienne de Martel

Reputation: 37015

I just tried your code, and I get:

1
[I@71f6f0bf

The thing is, your method takes an array of Object by varargs. So, for the first call, params is an array of 3 elements containing each individual Integer. However, ints are not Objects (int's Wrapper class, Integer, is, but int isn't), so for the second call, params is an array of a single element containing the actual array object. That gibberish above is the output of an array's toString() method.

If you would have replace the varargs call with a Object[], the second call would not have compiled, because an int[] is not a Object[].

Upvotes: 3

Object... interprets an array as a list of arguments, not as a single object. Why not use a Set as a container instead?

Upvotes: 0

soulcheck
soulcheck

Reputation: 36777

In java every function with (X... ) signature takes an array of X as parameter.

In your first example you get warning that you're passing the array of Integers as vararg Object without a cast. Java is clever enough to thing that you probably wanted to pass it as Object[] instead of a single Object. If you add a cast to Object[] the warning disappears.

In the second example the array is pàssed as only THE FIRST vararg, as every array is an object. It can't be passed as an array of object, because it's an array of primitives.

Arrays of any type are objects as you can verify running this snippet of code

public class Test{
    public static void test(Object a) {
        System.out.println("ok");
    }

    public static void main(String args[]){
        int[] i = {1,2,3,4};
        test(i);
    }
}

It prints "ok", which means that int[] is an Object. ~

Upvotes: 5

Related Questions