![](/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.