为什么打印 Java 数组会显示内存位置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14794930/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why does printing a Java array show a memory location
提问by dannyfrenton
int[] answer= new int[map.size()];
HashMap<String, Integer> map = new HashMap<String, Integer>();
for (int j=0; j<answer.length;j++){
int x=map.get(keys.get(j));
answer[j]=x;
}
return answer
When I print x
using System.out.println(x)
in the loop, I get values of 1, 2, 3
but when I return the answer and print it, I get [I@9826ac5
. Any idea why?
当我在循环中打印x
usingSystem.out.println(x)
时,我得到的值为 ,1, 2, 3
但是当我返回答案并打印它时,我得到[I@9826ac5
. 知道为什么吗?
回答by Dave
I[
is kind of the "class type" for an array of integer. Printing out this array itself will print the class type @
then a short hex string because that's the hash code of the array. It's the same as something you've probably seen like Object@0b1ac20
. This is implemented as the default toString()
for Object
.
I[
是整数数组的“类类型”。打印出这个数组本身将打印类类型,@
然后是一个简短的十六进制字符串,因为这是数组的哈希码。这与您可能见过的相同Object@0b1ac20
。这是作为默认toString()
的Object
。
Maybe you want to return a specific element of the array or print the whole array using a for loop?
也许您想返回数组的特定元素或使用 for 循环打印整个数组?
回答by redsaz
Long story short, you can't easily print an array in java. Do this:
长话短说,您不能在 java 中轻松打印数组。做这个:
System.out.println( Arrays.toString(answer) );
回答by Jigar Joshi
because that is how array's toString()
method is implemented
因为这就是数组toString()
方法的实现方式