Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chris-martin/ea2e091e2b8283601846 to your computer and use it in GitHub Desktop.
Save chris-martin/ea2e091e2b8283601846 to your computer and use it in GitHub Desktop.

https://stackoverflow.com/questions/24708810/why-is-int-considered-an-object-instead-an-array-of-objects

public class Foo {

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

    static void foo(Object o) {
        System.out.println("object");
    }

    static void foo(Object[] o) {
        System.out.println("array");
    }
}

Why does this print "object" instead of "array"?

The simple answer is that int[] isn't a subtype of Object[] because int isn't a subtype of Object.

Java's type hierarchy does not have a supremum, so unfortunately it's impossible to write a method with a parameter that can be any type of array. This is why, if you look at APIs like java.util.Arrays, you'll see a lot of methods that are repeated for byte[], char[], double[], float[], int[], long[], short[], and Object[].

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment