涼風炊 2021-03-25 23:40 采纳率: 100%
浏览 32
已采纳

关于哈希值和地址值的问题,在甲骨文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 这让我十分不能理解,求大神可以回复一下。

  • 写回答

2条回答 默认 最新

  • CSDN专家-ProfSnail 2021-03-26 01:53
    关注

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

    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提供的哈希函数生成一个哈希值的。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的