toString() 返回对象的字符串/文本表示。
toString() 方法通常用于调试、日志记录等诊断目的,用于读取有关对象的有意义的详细信息。
当对象传递给 println、print、printf、String.format()、assert 或字符串连接运算符时,会自动调用它。
Object 类中 toString() 的默认实现返回一个字符串,该字符串由该对象的类名后跟@符号和该对象的哈希码的无符号十六进制表示,使用以下逻辑,
getClass().getName() + "@" + Integer.toHexString(hashCode())
例如下面的
public final class Coordinates {
private final double x;
private final double y;
public Coordinates(double x, double y) {
this.x = x;
this.y = y;
}
public static void main(String[] args) {
Coordinates coordinates = new Coordinates(1, 2);
System.out.println("Bourne's current location - " + coordinates);
}
}
打印
Bourne's current location - Coordinates@addbf1 //concise, but not really useful to the reader
现在,在 Coordinates 类中覆盖 toString(),如下所示,
@Override
public String toString() {
return "(" + x + ", " + y + ")";
}
结果
Bourne's current location - (1.0, 2.0) //concise and informative
当在包含对这些对象的引用的集合上调用该方法时,覆盖 toString() 的用处会变得更大。比如下面的
public static void main(String[] args) {
Coordinates bourneLocation = new Coordinates(90, 0);
Coordinates bondLocation = new Coordinates(45, 90);
Map<String, Coordinates> locations = new HashMap<String, Coordinates>();
locations.put("Jason Bourne", bourneLocation);
locations.put("James Bond", bondLocation);
System.out.println(locations);
}
打印
{James Bond=(45.0, 90.0), Jason Bourne=(90.0, 0.0)}
而不是这个,
{James Bond=Coordinates@addbf1, Jason Bourne=Coordinates@42e816}
很少有实现指针,
-
您应该几乎总是覆盖 toString() 方法。 不需要覆盖的情况之一是实用程序类,它们以java.util.Math 的方式对静态实用程序方法进行分组。不需要覆盖的情况非常直观;几乎总是你会知道。
- 返回的字符串应该简洁明了,最好是一目了然。
- 至少,用于在两个不同对象之间建立等效性的字段,即在 equals() 方法实现中使用的字段应该由 toString() 方法吐出。
-
为返回的字符串中包含的所有实例字段提供访问器/获取器。例如,在坐标类中,
public double getX() {
return x;
}
public double getY() {
return y;
}
toString() 方法的全面介绍参见 Josh Bloch 所著的 Effective Java™ 第二版一书的第 10 条。