Question

I am using the following program in eclipse Kepler

import java.util.Arrays;

public class Mainn {
    public static void main(String[] args) {    
        int[] a = {1, 2};
        int[] b = {1, 2};

        System.out.println(Arrays.deepEquals(a, b));    
    }
}

It is giving me a compile time error about int[] arguments not being applicable for Object[] formal parameters. But the same program works fine when I use Integer[] instead of int[] as the data type of the arrays a and b.

I am confused by this. According to Java docs the compiler automatically autoboxes and unboxes between primitives and the wrapper classes so it should work here. But it isn't working. Why?

Was it helpful?

Solution

The rules for subtyping arrays are as follows, from the Java Language Specification, where > means is a supertype

If S and T are both reference types, then S[] > T[] iff S > T.

...

  • If P is a primitive type, then:
    • Object >1 P[]
    • Cloneable >1 P[]
    • java.io.Serializable >1 P[]

where >1 means is a direct supertype.

In this case S is Object and T is Integer, So because Integer is a subtype of Object and therefore Integer[] is a subtype of Object[], you can use it as an argument to a method that expects an Object[].

However, for int, which is a primitive, Object is the supertype of int[] and therefore int[] cannot be used where an Object[] is expected.

The notion of wrapper classes doesn't apply here.

OTHER TIPS

Auto-boxing applies to primitives like int (converted to Integer), but not to arrays - an object of type int[] is not automatically promoted to Integer[]

I don't have any specific sources for why this design choice was made, but there are a couple of points that seem relevant:

  • int[] is already an object, whereas auto-boxing applies to primitives. Auto-boxing int[] (and other cases) would complicate the criteria for auto-boxing significantly (potentially resulting in unexpected behavior in some cases)
  • Auto-boxing is not a zero-cost operation. Boxing int[] to Integer[] would mean creating a new array, then a new wrapper for every element in the array. In general Java tries to avoid doing costly operations implicitly.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top