Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many objects are in this 2-dimensional array? [closed]

Tags:

java

arrays

int x[][] = {{1, 2}, {3, 4}};

Since arrays are objects and 2-dimensional arrays are arrays of arrays, then how many objects are in this little piece of code?

like image 582
Kacy Raye Avatar asked Dec 26 '22 06:12

Kacy Raye


1 Answers

Three. One for the top level array of int[] objects, and two int[] objects.

The elements (the integers themselves) are not objects.


My criterion for being "an object" is something that has java.lang.Object as a direct or indirect supertype. All array types are implicitly subtypes of Object, but int is a primitive data type ... and not a subtype of Object.

The other thing to note is that int[][] means "array of int[]" ... in a very literal sense. The int[] objects that you find in an int[][] are real, first-class objects. Your declaration

    int[][] x = {{1,2}, {3,4}};

is a short-hand for this:

    int[][] x = new int[2][]();
    x[0] = new int[]{1, 2};
    x[1] = new int[]{3, 4};
like image 57
Stephen C Avatar answered Jan 21 '23 23:01

Stephen C