如何在 Java 中使用 toString 方法?

有人能给我解释一下 Object类中定义的 toString()方法的概念吗?它是如何使用的,它的目的是什么?

875722 次浏览

It may optionally have uses within the context of an application but far more often it is used for debugging purposes. For example, when you hit a breakpoint in an IDE, it's far easier to read a meaningful toString() of objects than it is to inspect their members.

对于 toString()方法应该做什么没有设定要求。按照约定,它通常会告诉您类的名称和相关数据成员的值。通常,toString()方法是在 IDE 中自动生成的。

Relying on particular output from a toString() method or parsing it within a program is a bad idea. Whatever you do, don't go down that route.

From the Object.toString docs:

类的字符串表示形式 一般来说,toString 方法返回一个字符串,该字符串 “文本表示”这个对象。 The result should be a concise but 信息表示,即 对一个人来说很容易阅读。它是 recommended that all subclasses override this method.

ObjecttoString方法 返回一个字符串,该字符串由 对象的类的名称 is an instance, the at-sign character “@”和无符号十六进制 类的哈希代码的表示形式 换句话说,这个方法 返回与值相等的字符串 以下人士:

getClass().getName() + '@' + Integer.toHexString(hashCode())

例如:

String[] mystr ={"a","b","c"};
System.out.println("mystr.toString: " + mystr.toString());


output:- mystr.toString: [Ljava.lang.String;@13aaa14a

除了 cletus 在调试方面的回答之外,每当您输出一个对象时都会使用它,比如当您使用

 System.out.println(myObject);

或者

System.out.println("text " + myObject);

The main purpose of toString is to generate a String representation of an object, means the return value is always a String. In most cases this simply is the object's class and package name, but on some cases like StringBuilder you will got actually a String-text.

Whenever you access an Object (not being a String) in a String context then the toString() is called under the covers by the compiler.

这就是原因

Map map = new HashMap();
System.out.println("map=" + map);

通过在您自己的类中重写 Object 中的标准 toString () ,您可以使您的对象在 String 上下文中也很有用。

(把它当成一个黑盒子! 永远不要把里面的东西拿出来给别人看)

toString()方法返回对象的 textual表示形式。java.lang.Object中已经包含了一个基本的实现,因此由于所有对象都继承自 java.lang.Object,因此可以保证 Java 中的每个对象都具有这个方法。

重写该方法总是一个好主意,特别是在调试时,因为调试器通常根据 toString()方法的结果显示对象。因此,使用一个有意义的实现,但将其用于 技术上的目的。应用程序逻辑应该使用 getter:

public class Contact {
private String firstName;
private String lastName;
public Contact (String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {return firstName;}
public String getLastName() {return lastName;}


public String getContact() {
return firstName + " " + lastName;
}


@Override
public String toString() {
return "["+getContact()+"]";
}
}

toString()将指定的对象转换为字符串值。

使用 String.toString:

无论何时您需要研究 String表单中名为 value 的构造函数,您都可以简单地使用 String.toString..。 举个例子。

package pack1;


import java.util.*;


class Bank {


String n;
String add;
int an;
int bal;
int dep;


public Bank(String n, String add, int an, int bal) {


this.add = add;
this.bal = bal;
this.an = an;
this.n = n;


}


public String toString() {
return "Name of the customer.:" + this.n + ",, "
+ "Address of the customer.:" + this.add + ",, " + "A/c no..:"
+ this.an + ",, " + "Balance in A/c..:" + this.bal;
}
}


public class Demo2 {


public static void main(String[] args) {


List<Bank> l = new LinkedList<Bank>();


Bank b1 = new Bank("naseem1", "Darbhanga,bihar", 123, 1000);
Bank b2 = new Bank("naseem2", "patna,bihar", 124, 1500);
Bank b3 = new Bank("naseem3", "madhubani,bihar", 125, 1600);
Bank b4 = new Bank("naseem4", "samastipur,bihar", 126, 1700);
Bank b5 = new Bank("naseem5", "muzafferpur,bihar", 127, 1800);
l.add(b1);
l.add(b2);
l.add(b3);
l.add(b4);
l.add(b5);
Iterator<Bank> i = l.iterator();
while (i.hasNext()) {
System.out.println(i.next());
}
}


}

... 把这个程序复制到你的 Eclipse 中,然后运行它... 你就会得到关于 String.toString的想法..。

正确重写 toString 方法有助于 Java 的日志记录和调试。

/**
* This toString-Method works for every Class, where you want to display all the fields and its values
*/
public String toString() {


StringBuffer sb = new StringBuffer();


Field[] fields = getClass().getDeclaredFields(); //Get all fields incl. private ones


for (Field field : fields){


try {


field.setAccessible(true);
String key=field.getName();
String value;


try{
value = (String) field.get(this);
} catch (ClassCastException e){
value="";
}


sb.append(key).append(": ").append(value).append("\n");


} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}


}


return sb.toString();
}

ToString () 返回对象的字符串/文本表示形式。 ToString ()方法通常用于调试、日志记录等诊断目的,用于读取关于对象的有意义的细节。

当对象被传递给 println、 print、 printf、 String.format ()、 asseration 或字符串串联运算符时,它会被自动调用。

Object 类中 toString ()的默认实现返回一个字符串,该字符串包含该对象的类名,后跟@sign,以及使用以下逻辑表示该对象的哈希代码的无符号十六进制表示形式,

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

现在,重写坐标类中的 toString () ,如下所示,

@Override
public String toString() {
return "(" + x + ", " + y + ")";
}

results in

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);
}

prints

{James Bond=(45.0, 90.0), Jason Bourne=(90.0, 0.0)}

而不是这样,

{James Bond=Coordinates@addbf1, Jason Bourne=Coordinates@42e816}

几个实现指南,

  1. You should almost always override the toString() method. One of the cases where the override wouldn't be required is utility classes that group static utility methods, in the manner of Java.util 数学. The case of override being not required is pretty intuitive; almost always you would know.
  2. 返回的字符串应该是简明和信息丰富的,理想情况下应该是不言而喻的。
  3. 至少,用于在两个不同对象之间建立等价关系的字段,即 等于()方法实现中使用的字段应该由 toString ()方法输出。
  4. 为返回的字符串中包含的所有实例字段提供访问器/getters。例如,在坐标类中,

    public double getX() {
    return x;
    }
    public double getY() {
    return y;
    }
    

A comprehensive coverage of the toString() method is in Item 10 of the book, Effective Java™, Second Edition, By Josh Bloch.

Coding:

public class Test {


public static void main(String args[]) {


ArrayList<Student> a = new ArrayList<Student>();
a.add(new Student("Steve", 12, "Daniel"));
a.add(new Student("Sachin", 10, "Tendulkar"));


System.out.println(a);


display(a);


}


static void display(ArrayList<Student> stu) {


stu.add(new Student("Yuvi", 12, "Bhajji"));


System.out.println(stu);


}


}

Student.java:

public class Student {


public String name;


public int id;


public String email;


Student() {


}


Student(String name, int id, String email) {


this.name = name;
this.id = id;
this.email = email;


}


public String toString(){           //using these toString to avoid the output like this [com.steve.test.Student@6e1408, com.steve.test.Student@e53108]
return name+" "+id+" "+email;
}




public String getName(){


return name;
}


public void setName(String name){


this.name=name;
}


public int getId(){


return id;
}


public void setId(int id){


this.id=id;
}


public String getEmail(){


return email;


}


public void setEmail(String email){


this.email=email;
}
}

产出:

[Steve 12 Daniel, Sachin 10 Tendulkar]

[Steve 12 Daniel, Sachin 10 Tendulkar, Yuvi 12 Bhajji]

If you are not used toString() in Pojo(Student.java) class,you will get an output like [com.steve.test.Student@6e1408, com.steve.test.Student@e53108].To avoid these kind of issue we are using toString() method.

如果你先学 Python 再学 Java。我认为它和 Python 中的 __str__()方法扮演着同样的角色,它是一个 神奇的方法,就像 __dict__()__init__()一样,但是它引用了一个表示对象的字符串。