Java 中 toString 方法的实现
Implementation of toString method in Java
当我想打印一个Boolean
(引用类型)的空数组时,结果是输出#1.但是当我想打印一个原始布尔类型的空数组时,输出#2就是结果。我知道 Object
class 中的 toString()
方法默认是 运行 。该方法的默认实现如下:
this.getClass().getName() + "@" + Integer.toHexString(this.hashCode());
不过有趣的是why Z写在原始类型的输出中然而对于int是I?
public class ToStringApp {
public static void main(String[] args) {
Boolean[] refs = new Boolean[1];
System.out.println(refs);
// output #1: [Ljava.lang.Boolean;@3764951d
boolean[] prims = new boolean[1];
System.out.println(prims);
// output #2: [Z@4b1210ee
int[] ints = new int[0];
System.out.println(ints);
// output #3: [I@4d7e1886
}
}
Class
的 getName()
的 Javadoc 是这么说的:
String java.lang.Class.getName()
Returns the name of the entity (class, interface, array
class,primitive type, or void) represented by this Class object,as a
String.
...
If this class object represents a class of arrays, then the
internal form of the name consists of the name of the element type
preceded by one or more '[' characters representing the depth of the
array nesting. The encoding of element type names is as follows:
Element Type
Encoding
boolean
Z
byte
B
char
C
class or interface
Lclassname;
double
D
float
F
int
I
long
J
short
S
如您所见,B
已被 byte
使用,因此 boolean
需要一个不同的字母。
当我想打印一个Boolean
(引用类型)的空数组时,结果是输出#1.但是当我想打印一个原始布尔类型的空数组时,输出#2就是结果。我知道 Object
class 中的 toString()
方法默认是 运行 。该方法的默认实现如下:
this.getClass().getName() + "@" + Integer.toHexString(this.hashCode());
不过有趣的是why Z写在原始类型的输出中然而对于int是I?
public class ToStringApp {
public static void main(String[] args) {
Boolean[] refs = new Boolean[1];
System.out.println(refs);
// output #1: [Ljava.lang.Boolean;@3764951d
boolean[] prims = new boolean[1];
System.out.println(prims);
// output #2: [Z@4b1210ee
int[] ints = new int[0];
System.out.println(ints);
// output #3: [I@4d7e1886
}
}
Class
的 getName()
的 Javadoc 是这么说的:
String java.lang.Class.getName()
Returns the name of the entity (class, interface, array class,primitive type, or void) represented by this Class object,as a String. ... If this class object represents a class of arrays, then the internal form of the name consists of the name of the element type preceded by one or more '[' characters representing the depth of the array nesting. The encoding of element type names is as follows:
Element Type Encoding boolean Z byte B char C class or interface Lclassname; double D float F int I long J short S
如您所见,B
已被 byte
使用,因此 boolean
需要一个不同的字母。