Kieran M
Kieran M

Reputation: 461

Outputting elements of an array with Arrays.toString()

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

Answers (4)

Solomon Alan-Dei
Solomon Alan-Dei

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

gati sahu
gati sahu

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

Youcef LAIDANI
Youcef LAIDANI

Reputation: 59960

You can use deepToString instead of toString:

System.out.println(Arrays.deepToString(newArray));

Upvotes: 12

Nisal Edu
Nisal Edu

Reputation: 7591

Try

Arrays.deepToString(newArray)

Upvotes: 3

Related Questions