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
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
It prints “ok”, which means that int[] is an Object.
~