[英]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. 我已经使用下面的代码来创建和填充数组,但是,当涉及到打印数组时,我没有得到我在使用
Arrays.toString()
函数时得到的结果。
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
. 根据您的需要,确保您声明的阵列是
one-dimensional
。 You declared a two dimensional array
which you are not using correctly. 您声明了一个未正确使用的
two dimensional array
。
Change int[][] newArray to int[] newArray
将
int[][] newArray to int[] newArray
更改int[][] newArray to int[] newArray
when you call toString(Object[] a)
internally it will call Object.toString method. 当你
toString(Object[] a)
内部调用toString(Object[] a)
,它将调用Object.toString方法。
(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. 如果你想要打印所有元素,那么你必须使用
deepToString
而不是toString
方法。对于一个对象类型数组,它将遍历数组并转换为字符串。
For an example every array element in your case is int array will call toString. 例如,在您的情况下,每个数组元素都是int数组将调用toString。
if (eClass.isArray()) {
if (eClass == int[].class)
buf.append(toString((int[]) element));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.