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

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章