gpt4 book ai didi

java - 在数组索引处打印值返回哈希码

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:02:30 25 4
gpt4 key购买 nike

只是尝试在二维数组中显示值并注意到我的代码打印了一些 hashcodes 然后是值。但我并没有打印数组对象本身(如帖子 here 中所做的那样)或至少显式调用数组对象的 toStringhashcode 方法。相反,我使用 arrayObj[i]arrayObj[i][j] 直接访问和打印数组中的值。

这是我的代码:

class PrintTwoDimArray {
public int [][] createArray () {
int counter = 0;
int[][] intArray = new int [2][4];
for (int i = 0; i < intArray.length; i++) {
for (int j = 0; j < intArray[i].length; j++) {
intArray[i][j] = ++counter;
}
}
return intArray;
}
public void printArray ( int [][] arrayObj ) {
for (int i = 0; i < arrayObj.length; i++) {
System.out.print(arrayObj[i] + " ");
for (int j = 0; j < arrayObj[i].length; j++) {
System.out.print(arrayObj[i][j] + " ");
}
System.out.println();
}
}
}

class TestPrintTwoDimArray {
public static void main (String[] args) {

PrintTwoDimArray twoDim = new PrintTwoDimArray();
int [][] multiArray = new int [2][4];
multiArray = twoDim.createArray();
twoDim.printArray(multiArray);
}
}

我的输出如下:

enter image description here

似乎我的代码以某种方式调用了数组的 toStringhashcode 方法。想法?如何修改以仅打印值?

javac和java版本1.8.0

最佳答案

二维数组是数组的数组。您创建的数组 (int[2][4]) 如下所示

[ 0 ] -> [ 1, 2, 3, 4 ]
[ 1 ] -> [ 5, 6, 7, 8 ]

因此,当您只访问第一个维度时,您将获得包含第二个维度的数组。

int[][] arr = createArray();
System.out.println(arr[0]);

会输出类似

的内容
[I@1db9742

要打印数组的值,您可以使用 Arrays.toString(arr)。在这种情况下,您可以省略内部循环,因为 Arrays.toString() 会为您完成。

 public void printArray ( int [][] arrayObj ) {
for (int i = 0; i < arrayObj.length; i++) {
System.out.println(Arrays.toString(arrayObj[i]));
}
}

关于java - 在数组索引处打印值返回哈希码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26943983/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com