Java 打印对象的地址

一、System 函数

  Java 获取不到对象的地址,但是可以获取对象的 hashcode,对象的 hashcode 在某种意义上就相当于对象的地址,hashCode 是用来在散列存储结构中确定对象的存储地址的。
  Object 的 hashCode() 默认是返回对象的哈希码,可以反应对象的内存地址,但是 hashCode() 可以重写,所以 hashCode() 不能绝对反应对象的内存地址。
  java.lang.System 类的方法 identityHashCode() 可以返回对象的哈希码(在一定程度上反应出对象的内存地址),不管该对象的类是否重写了 hashCode() 方法。源码如下所示。

	/**
     * 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.
     *
     * @param x object for which the hashCode is to be calculated
     * @return  the hashCode
     * @since   JDK1.1
     */
    public static native int identityHashCode(Object x);

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

二、实战代码
	public static void main(String[] args) {
    
    
        String a = "a";
        System.out.println(a.hashCode());               // 97
        System.out.println(System.identityHashCode(a)); // 1392838282
        String b = a;
        System.out.println(b.hashCode());               // 97
        System.out.println(System.identityHashCode(b)); // 1392838282
        System.out.println(a == b);                     // true
        a = "b";
        System.out.println(a.hashCode());               // 98
        System.out.println(System.identityHashCode(a)); // 523429237
        System.out.println(b.hashCode());               // 97
        System.out.println(System.identityHashCode(b)); // 1392838282
        System.out.println(a);                          // b
        System.out.println(b);                          // a
    }

  要想真实地反应对象的内存地址,应使用 System.identityHashCode() 方法。

猜你喜欢

转载自blog.csdn.net/piaoranyuji/article/details/125482763