Is an array a primitive type or an object (or something else entirely)?

asteri picture asteri · Oct 9, 2012 · Viewed 54k times · Source

The question is basically self-explanatory. I haven't been able to find an API for arrays (other than this Arrays, but this just defines a bunch of static helper functions for dealing with actual arrays). If there is no class for it, this seems to suggest that an array can't be an Object.

However, the fact that an array has public fields like length and methods that it can invoke like .equals() and .clone() seem to suggest (very strongly) the complete opposite.

What is the explanation for the odd presentation and behavior of primitive arrays?

As a note, I tried to use the "Open Implementation" Eclipse feature on the .clone() method of an array just now, hoping that I would be able to look at where and how this method was defined (since it said int[] overrode it from Object), but it actually caused my entire Eclipse to freeze up and crash...

Answer

irreputable picture irreputable · Oct 9, 2012

There is a class for every array type, so there's a class for int[], there's a class for Foo[]. These classes are created by JVM. You can access them by int[].class, Foo[].class. The direct super class of these classes are Object.class

public static void main(String[] args)
{
    test(int[].class);
    test(String[].class);
}

static void test(Class clazz)
{
    System.out.println(clazz.getName());
    System.out.println(clazz.getSuperclass());
    for(Class face : clazz.getInterfaces())
        System.out.println(face);
}

There's also a compile-time subtyping rule, if A is subtype of B, A[] is subtype of B[].