[英]Outputting elements of an array with Arrays.toString()
我已經使用下面的代碼來創建和填充數組,但是,當涉及到打印數組時,我沒有得到我在使用Arrays.toString()
函數時得到的結果。
而不是打印
newArray: [2, 4, 6]
newArray: [8, 10, 12]
etc..
它打印
newArray: [[I@15db9742, [I@6d06d69c, [I@7852e922, [I@4e25154f]
newArray: [[I@15db9742, [I@6d06d69c, [I@7852e922, [I@4e25154f]
etc..
編碼:
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));
}
}
任何有關這方面的幫助將非常感激。
您可以使用deepToString
而不是toString
:
System.out.println(Arrays.deepToString(newArray));
嘗試
Arrays.deepToString(newArray)
根據您的需要,確保您聲明的陣列是one-dimensional
。 您聲明了一個未正確使用的two dimensional array
。
將int[][] newArray to int[] newArray
更改int[][] newArray to int[] newArray
當你toString(Object[] a)
內部調用toString(Object[] a)
,它將調用Object.toString方法。
(obj == null) ? "null" : obj.toString();
如果你想要打印所有元素,那么你必須使用deepToString
而不是toString
方法。對於一個對象類型數組,它將遍歷數組並轉換為字符串。
例如,在您的情況下,每個數組元素都是int數組將調用toString。
if (eClass.isArray()) {
if (eClass == int[].class)
buf.append(toString((int[]) element));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.