Printing value at array index returns hashcode
Just playing around with displaying values ββin a 2D array and noticing that my code is printing multiple hashcodes
and then values. But I am not printing the array object itself (as done in the post here ), or at least explicitly calling a method toString
or hashcode
array object. Instead, I directly get and print the values ββin the array using arrayObj[i]
and arrayObj[i][j]
.
Here's my code:
class PrintTwoDimArray {
public int [][] createArray () {
int counter = 0;
int[][] intArray = new int [2][4];
for (int i = 0; i < intArray.length; i++) {
for (int j = 0; j < intArray[i].length; j++) {
intArray[i][j] = ++counter;
}
}
return intArray;
}
public void printArray ( int [][] arrayObj ) {
for (int i = 0; i < arrayObj.length; i++) {
System.out.print(arrayObj[i] + " ");
for (int j = 0; j < arrayObj[i].length; j++) {
System.out.print(arrayObj[i][j] + " ");
}
System.out.println();
}
}
}
class TestPrintTwoDimArray {
public static void main (String[] args) {
PrintTwoDimArray twoDim = new PrintTwoDimArray();
int [][] multiArray = new int [2][4];
multiArray = twoDim.createArray();
twoDim.printArray(multiArray);
}
}
My output looks like this:
It seems that my code is calling a method toString
or hashcode
array in some way . Thoughts? How do I change printable values ββonly?
javac and java version 1.8.0
source to share
A 2D array is an array of arrays. The array ( int[2][4]
) being created looks like this:
[ 0 ] -> [ 1, 2, 3, 4 ]
[ 1 ] -> [ 5, 6, 7, 8 ]
So when you only access the first dimension, you will end up with an array containing the second dimension.
int[][] arr = createArray();
System.out.println(arr[0]);
will output something like
[I@1db9742
To print the values ββof an array, you can use Arrays.toString(arr)
. In this case, you can omit the inner loop because it Arrays.toString()
does it for you.
public void printArray ( int [][] arrayObj ) {
for (int i = 0; i < arrayObj.length; i++) {
System.out.println(Arrays.toString(arrayObj[i]));
}
}
source to share
When printing
arrayObj[i]
you get the default Object
toString()
from the array. You can use Arrays.toString(int[])
to do String
like
System.out.println(Arrays.toString(arrayObj[i]));
Alternatively you can use Arrays.deepToString(Object[])
to print your multidimensional array without loop
System.out.println(Arrays.deepToString(arrayObj));
Edit
You can use formatted output to create your table.
public static void printArray(int[][] arrayObj) {
for (int i = 0; i < arrayObj.length; i++) {
System.out.printf("%03d: ", i + 1);
for (int val : arrayObj[i]) {
System.out.printf("% 4d ", val);
}
System.out.println();
}
}
public static void main(String[] args) {
int[][] table = { { 3, 1, 2 }, { 5, 1, 4 }, { 100, 200, 300 } };
printArray(table);
}
Output
001: 3 1 2
002: 5 1 4
003: 100 200 300
source to share