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

}

  • 18
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

明月几时有666

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值