通常,当我尝试使用System.out.println();
打印对象时
class Car {
String color = "red";
}
class Main {
public static void main(String[] args) {
Car car = new Car();
System.out.println(car);
}
}
输出类似于:
Car@677327b6
哪个是其class name
+ '@'
+ hashCode
。在内部,它正在调用toString()
方法。好像很好但是,当我实现如下自动装箱时会发生什么:
class Main {
public static void main(String[] args) {
int i = 100;
Integer obj = i;
System.out.println(obj);
}
}
此处输出为100
。为什么不像Main@hexcode
?我以为我正在将原语i
转换为Integer
类型的对象。请纠正我。
答案 0 :(得分:4)
Class @ hashCode是Object.toString()
的默认返回值。 Integer
类overrides toString()
。
public String toString()
返回表示此
String
值的Integer
对象。该值将转换为带符号的十进制表示形式,并作为字符串返回,就像整数值作为toString(int)
方法的参数一样。返回:
以10为基数的此对象的值的字符串表示形式。