class 对象和 java 中的包装器 class 对象有什么区别
What is the difference between a normal class object and a wrapper class object in java
通常当我尝试使用 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
类型的对象。请指正。
Class@hashCode 是 Object.toString()
. The Integer
class overrides toString()
.
的默认 return 值
public String toString()
Returns a String
object representing this Integer
's value. The value is converted to signed decimal representation and returned as a string, exactly as if the integer value were given as an argument to the toString(int)
method.
Overrides:
toString
in class Object
Returns:
a string representation of the value of this object in base 10.
通常当我尝试使用 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
类型的对象。请指正。
Class@hashCode 是 Object.toString()
. The Integer
class overrides toString()
.
public String toString()
Returns a
String
object representing thisInteger
's value. The value is converted to signed decimal representation and returned as a string, exactly as if the integer value were given as an argument to thetoString(int)
method.Overrides:
toString
in classObject
Returns:
a string representation of the value of this object in base 10.