System.out.println(object) 的输出 [英] Output of System.out.println(object)

查看:38
本文介绍了System.out.println(object) 的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道执行以下操作时的确切输出是什么.

class 数据 {int a = 5;}类主要{公共静态无效主(字符串 [] args){数据 dObj = 新数据();System.out.println(dObj);}}

我知道它给出了一些与对象相关的东西,因为在我的例子中输出是 data@1ae73783.我猜 1ae73783 是一个十六进制数.我也做了一些工作并打印了

System.out.println(dObj.hashCode());

我得到了号码415360643.我得到了一个整数值.我不知道 hashCode() 返回什么,仍然出于好奇,当我将 1ae73783 转换为十进制时,我得到了 415360643

这就是为什么我很好奇这个数字到底是什么.这是 Java 沙箱的某个内存位置还是其他什么?

解决方案

发生的事情是默认的 toString() 类的方法正在被使用.该方法定义如下:

<块引用>

Object 类的 toString 方法返回一个字符串,该字符串由对象是其实例的类的名称、at 符号字符@"组成,以及对象哈希码的无符号十六进制表示.换句话说,这个方法返回一个等于以下值的字符串:

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

默认返回的值 hashCode() 方法是特定于实现的:

<块引用>

在合理可行的情况下,Object 类定义的 hashCode 方法确实为不同的对象返回不同的整数.(这通常通过将对象的内部地址转换为整数来实现,但 JavaTM 编程语言不需要这种实现技术.)

I want to know what exactly the output is when I do the following.

class Data {
  int a = 5;
}

class Main {
  public static void main(String[] args) {
    data dObj = new data();
    System.out.println(dObj);
  }
}

I know it gives something related to object as the output in my case is data@1ae73783. I guess the 1ae73783 is a hex number. I also did some work around and printed

System.out.println(dObj.hashCode());

I got the number 415360643. I got an integer value. I don't know what hashCode() returns, still out of curiosity, when I converted 1ae73783 to decimal, I got 415360643!

That's why I am curious about what exactly is this number. Is this some memory location of Java's sandbox or some other thing?

解决方案

What happens is that the default toString() method of your class is getting used. This method is defined as follows:

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())

The value returned by the default hashCode() method is implementation-specific:

As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)

这篇关于System.out.println(object) 的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆