关于哈希值和地址值的问题,在甲骨文SE11认定资格考试书中出现的问题。

 int[] array = new int[0];

System.out.println(array);  

执行后有7个选项

A : 0

B: null

C: 什么都显示

D: { }

E: 显示哈希值  

F:编译错误

G:抛出异常

书给的是正确答案为E

我自己在电脑上码了一下,返回值为一个地址值,

但是我看的教科书说  toString方法的原代码为

return getClass().getName()+"@"+Integer.toHexString(hashCode());

所以返回值为hashCode 这让我十分不能理解,求大神可以回复一下。

我在源码里面找到这样的解释说明:

Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.
The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:
       getClass().getName() + '@' + Integer.toHexString(hashCode())
       
Returns:
a string representation of the object.

翻译一下是这样的:

返回一个字符串来表示这个对象。一般而言,toString这个方法返回一个字符串,使用“文本方式”来代表此对象。这个结果应该是一个简洁但是有信息量、有代表性的,能够让人很容易的就能读懂接受。推荐所有的子类型复写这个toString方法。

toString方法对于类对象返回一个字符串,如果这个对象是一个实例的话,返回的字符串就包含类名,并且有@字符,以及无符号的十六进制数字,表示这个对象的哈希值。换句话来说,这个方法返回的字符串等价于:

    getClass().getName()+'@'+Integer.toHexString(hashCode())

 

所以对于array进行打印的时候,会先调用toString这个函数,将这个array对象打印出来。打印的字符串就是该对象的类名@这个对象的哈希值。

至于题主说自己再电脑上码了一下,返回值是一个地址值,其实你看到的那一串数字是类似于地址值一样的,该对象的哈希值。每一个对象都可以由java提供的哈希函数生成一个哈希值的。

您好,我是问答小助手,你的问题已经有小伙伴为您解答了问题,您看下是否解决了您的问题,可以追评进行沟通哦~

如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~

ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632