An array reference variable 无法保存 char 数组的地址 在 Java 中。

huangapple go评论111阅读模式
英文:

why an array reference variable cant hold address for char array in java?

问题

我想要打印字符数组的地址。当我尝试这样做时,我得到了一个字符串输出“ABC”,而不是得到字符数组的地址。

英文:

I want to print the address of the char array. When I try to do it I am getting a string output as "ABC" instead of getting address of the char array.

class P
{
    public static void main(String [] args)
    {
        char [] ch = {'A','B','C'};
        System.out.println(ch);
    }
}

答案1

得分: 2

对于大多数对象,如果你将它们传递给 println,你会得到对象的正常 toString() 表示。对于数组,它看起来像 [C@6d4b1c02

然而,有一种专门用于接受 char 数组的 println 版本。所以如果你调用它,你不会得到数组的 toString() 表示,而是得到数组的内容,在这种情况下是 ABC

如果你调用普通(非 char[])版本的 println

System.out.println((Object) ch);

你将得到难以理解的 [C@6d4b1c02 输出。

英文:

For most objects, if you pass them to println, you get the normal toString() representation of the object. For arrays, it looks something like [C@6d4b1c02.

However, there is a version of println written specifically to accept a char array. So if you call that, you don't get the toString() representation of the array; you get the contents of the array, in this case ABC.

If you were to call the ordinary (non-char[]) version of println

System.out.println((Object) ch);

you would get the impenetrable [C@6d4b1c02 output.

答案2

得分: 0

以下是已翻译的部分:

你可以查看 println(char[] ch) 的实现,针对 char[] 它最终调用以下方法:

public void write(char cbuf[]) throws IOException {
    write(cbuf, 0, cbuf.length);
}

这个方法从数组的第 0 个元素写入到数组的长度,这就是为什么你会得到 ABC

如果你想要哈希码类型的值,你可以更改你的方法:

System.out.println(ch.toString());
英文:

You can look into println(char[] ch) implementation for char[] it finally calls below method

 public void write(char cbuf[]) throws IOException {
        write(cbuf, 0, cbuf.length);
    }

This method write array element from 0 to array length that why you are getting ABC.

If you want hash code kind of value you can change your method

 System.out.println(ch.toString());

huangapple
  • 本文由 发表于 2020年8月14日 17:04:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/63409783.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定