Java打印String对象的地址

一、System函数
当使用System.out.println()方法打印String类型对象时,会输出String对象代表的字符串,并不会输出对象的地址。因此,我们必须借助其他API来实现该功能。

java.lang.System类的方法

public static native int identityHashCode(Object x);
Returns the same hash code for the given object as would be returned by the default method hashCode(), whether or not the given object’s class overrides hashCode(). The hash code for the null reference is zero.
Params: x – object for which the hashCode is to be calculated
Returns: the hashCode

无论给定对象的类是否覆盖hashCode(),返回给定对象的哈希码与默认hashCode()方法返回的哈希码相同。空引用的哈希码是零。默认hashCode()方法,即Object对象中的hashCode()方法

public native int hashCode();
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)

在合理可行的情况下,由 Object 类定义的 hashCode() 方法为不同的对象返回不同的整数。 (通常将对象的内部地址转换为整数),也就是说Object类的hashcode()方法返回对象的地址。

二、实现代码
一般,被打印的对象的形式为:java.lang.Object@1ff9dc36,由全限定类名+@+十六进制数组成。

为了打印的字符串对象的形式和一般形式相同,我们还需要使用另外两个方法,

String.class.getName() 返回全限定类名java.lang.String;
Integer.toHexString(int) 将十进制数转换为十六进制数并返回;

代码如下及运行结果:

 参考代码:

复制代码
public class StringObjectAddrTest {

    public static void main(String[] args) {

        String str = "HelloWorld";
        System.out.println(String.class.getName() + "@" + Integer.toHexString(System.identityHashCode(str)));

        // 与Object对比
        System.out.println(new Object());
    }

}
复制代码

 

posted @   super超人  阅读(690)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
· 使用C#创建一个MCP客户端
历史上的今天:
2017-02-27 window.location.href=*.html访问没反应问题
点击右上角即可分享
微信分享提示