Reputation: 461
I have used the code below to create and populate an array, however, when it comes to printing the array I do not get the result I expect while using the Arrays.toString()
function.
Rather than printing
newArray: [2, 4, 6]
newArray: [8, 10, 12]
etc..
it prints
newArray: [[I@15db9742, [I@6d06d69c, [I@7852e922, [I@4e25154f]
newArray: [[I@15db9742, [I@6d06d69c, [I@7852e922, [I@4e25154f]
etc..
The code:
public static void main(String[] args) {
int[][] newArray = new int[4][3];
int number = 2;
for (int rowCounter = 0; rowCounter < newArray.length; rowCounter++) {
for (int colCounter = 0; colCounter < newArray[rowCounter].length; colCounter++) {
newArray[rowCounter][colCounter] = number;
number += 2;
}
System.out.println("newArray: " + Arrays.toString(newArray));
}
}
Any help with this would be much appreciated.
Upvotes: 6
Views: 1845
Reputation: 41
With the result you desire, make sure the array you are declaring is one-dimensional
. You declared a two dimensional array
which you are not using correctly.
Change int[][] newArray to int[] newArray
Upvotes: 3
Reputation: 2626
when you call toString(Object[] a)
internally it will call Object.toString method.
(obj == null) ? "null" : obj.toString();
If you want to print all element then as mentioned you have to deepToString
instead of toString
method.Internally it will for a object type array will loop through the array and convert to string.
For an example every array element in your case is int array will call toString.
if (eClass.isArray()) {
if (eClass == int[].class)
buf.append(toString((int[]) element));
Upvotes: 2
Reputation: 59960
You can use deepToString
instead of toString
:
System.out.println(Arrays.deepToString(newArray));
Upvotes: 12