简体   繁体   中英

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.

您可以使用deepToString而不是toString

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

尝试

Arrays.deepToString(newArray)

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

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM