![](/img/trans.png)
[英]Why System.out.println prints the elements of an arraylist and not the hashcode of the object?
[英]System.out.println prints different Strings on the same Object type using getClass()
我已經閱讀了這個問題,但我並不完全滿意。 這是我的代碼:
public static void main(String args[]){
Car c = new Car();
System.out.println(c);
System.out.println(c.getClass());
}
輸出:
Car@xxx
Car
而且我不明白為什么在第一種情況下它也打印 hashCode 而在第二種情況下不打印。 我已經看到了println(Object obj)
是如何定義的以及它使用的方法,它們都是一樣的,其實在堆棧調用的最深層次上, toString()
是這樣定義的:
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
那么為什么在輸出中我看不到“@xxx”呢?
先感謝您。
因為getClass()會返回Class
的實例
public final Class<?> getClass()
當您打印Class
實例時,會調用 toString 返回名稱,這是 Java 中Class
的toString實現
public String toString() {
return (isInterface() ? "interface " : (isPrimitive() ? "" : "class "))
+ getName();
}
Class.toString
的定義不同,准確地生成您看到的輸出。 它只是打印類的名稱。 在該類中沒有調用過Object.toString
默認值
在下面的語句中,調用了Car
toString()
方法:
System.out.println(c);
在下面的語句中,調用了Class
toString()
方法:
System.out.println(c.getClass());
既然你沒有覆蓋的toString()
方法Car
的的toString()方法Object
獲取調用給你喜歡的輸出Car@xxx
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.