Reputation: 97
Can a two-dimensional array of primitive data type contain elements of different types? I have read articles that suggest it both can and cannot.
Upvotes: 3
Views: 2569
Reputation: 17454
Can a two-dimensional array of primitive data type contain elements of different types? I have read articles that suggest it both can and cannot
Using int
array as an example:
int[] nums1; //Array of integers
int[][] nums2; //Array of (Array of integers)
int[][][] nums3; //Array of (Array of (Array of integers))
So if you perceive 2D arrays as a table with rows and columns are if you are asking whether the table can contains different datatype in different rows, the answer is no.
But since multi-dimensional arrays are merely array of array(s), in actual fact, they are indeed holding data of different types: one is holding int
the other is holding an array (an object)
.
Upvotes: 0
Reputation: 2148
A two-dimensional array of a primitive type such as int
isn't technically only of primitive types. The outer array contains an array of int[]
arrays, which are in fact Object
s - not a primitive type (int[]
is a subtype of Object
).
This means that an int[][]
array could contain null
, while the inner int[]
arrays can only contain primitive int
s. An int[][]
array cannot however, contain an element of any type other than int[]
.
Demonstration
This code compiles and executes with no exceptions:
int[][] a = {{1, 2, 3}, {4, 5, 6}, null};
System.out.println(Arrays.deepToString(a));
Object b = a;
System.out.println(Arrays.deepToString((int[][]) b));
int[][] c = a;
System.out.println(Arrays.deepToString(c));
int[] d = a[1];
System.out.println(Arrays.toString(d));
Object e = d;
System.out.println(Arrays.toString((int[]) e));
int[] f = a[2];
System.out.println(Arrays.toString(f));
And will output:
[[1, 2, 3], [4, 5, 6], null]
[[1, 2, 3], [4, 5, 6], null]
[[1, 2, 3], [4, 5, 6], null]
[4, 5, 6]
[4, 5, 6]
null
Upvotes: 2
Reputation: 2424
In response to Nem's comment, I'd suggest you want to have a 2d array of a common interface, that way the container (2d array) can hold the different types. It would make more sense to another programmer when seeing the array of that interface, rather than an array of Object. Also using the "instanceof" operator to check the specific implementation of said interface.
I can provide an example if needed.
Upvotes: 0