1. Why override toString methods?

public class Person { protected String name; protected int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Person(String name, int age) { super(); this.name = name; this.age = age; } /*@Override public String toString() { return "Person [name=" + name + ", age=" + age + "]"; }*/ public static void main(String[] args) { Person s = new Person("liming", 6); System.out.println(s); }}Copy the code

If not overwritten print:

demo6.Person@1636731
Copy the code

Overlay printing:

@Override public String toString() { return "\nname: " + name + "\nage: " + age; }Copy the code
Person [name=liming, age=6]
Copy the code

Although java.lang.object provides an implementation of the toString method, the string it returns is usually not what users of the class expect to see.

While “Person@1636731” is considered concise and easy to read, it’s not as informative as “Person [name=liming, age=12]”. It contains the name of the class, along with an “@” symbol, followed by an unsigned hexadecimal representation of the hash code, such as “Person@1636731”.

The toString convention further states that it is recommended that all classes override this method.

2. Whether you specify the format or not, specify it in the document

  • Whether or not you specify a format provides a programmatic access path to the information contained in the toString return value
  • Whether or not, make your intentions clear in the document

The general convention of the toString() method is to return a “concise, yet informative, and easy-to-read representation” of the current object.

The format for specifying the toString return value is flawed: if the class is already widely used, once you specify the format, you must stick to it consistently. Whether or not you decide to specify a format, the intent should be clearly stated in the document.

Guava on toString

Guava provides an easy way to create toStrings through objects.toStringHelper. Take a look at the following example:

/ Returns "ClassName{x=1}"
   Objects.toStringHelper(this)
       .add("x", 1)
       .toString();

   // Returns "MyObject{x=1}"
   Objects.toStringHelper("MyObject")
       .add("x", 1)
       .toString();
Copy the code

==Guava documentation link on toString == : code.google.com/p/guava-lib…

// Rewrite PhoneNumber’s toString method – Effective Java Chinese 2nd edition, page 44

package org.effectivejava.examples.chapter03.item10; import java.util.HashMap; import java.util.Map; import com.google.common.base.Objects; public final class PhoneNumber { private final short areaCode; private final short prefix; private final short lineNumber; public PhoneNumber(int areaCode, int prefix, int lineNumber) { rangeCheck(areaCode, 999, "area code"); rangeCheck(prefix, 999, "prefix"); rangeCheck(lineNumber, 9999, "line number"); this.areaCode = (short) areaCode; this.prefix = (short) prefix; this.lineNumber = (short) lineNumber; } private static void rangeCheck(int arg, int max, String name) { if (arg < 0 || arg > max) throw new IllegalArgumentException(name + ": " + arg); } @Override public boolean equals(Object o) { if (o == this) return true; if (! (o instanceof PhoneNumber)) return false; PhoneNumber pn = (PhoneNumber) o; return pn.lineNumber == lineNumber && pn.prefix == prefix && pn.areaCode == areaCode; } @Override public int hashCode() { int result = 17; result = 31 * result + areaCode; result = 31 * result + prefix; result = 31 * result + lineNumber; return result; }} @override public String toString() {return * string. format("(%03d) %03d-%04d", areaCode, prefix, lineNumber); @override public String toString() {return objects.toStringHelper (this); .addValue(String.format("(%03d) %03d-%04d", areaCode, prefix,lineNumber)) .add("areaCode", areaCode) .add("prefix", prefix) .add("lineNumber", lineNumber) .toString(); } public static void main(String[] args) { Map<PhoneNumber, String> m = new HashMap<PhoneNumber, String>(); m.put(new PhoneNumber(707, 867, 5309), "Jenny"); System.out.println(m); }}Copy the code

Output contrast

PhoneNumber{(707) 867-5309, areaCode=707, prefix=867, lineNumber=5309}=Jenny}Copy the code

4. Conclusion

Overwriting toString is to make debugging or printing easier to see useful information about an object, so it is recommended to overwrite toString when writing a new class.

5. References

www.jianshu.com/p/05bf27bb2… www.javatt.com/p/6191

Pay attention to the public account “Programmer interview”

Reply to “interview” to get interview package!!

This public account to share their own from programmer xiao Bai to experience spring recruitment autumn recruitment cut more than 10 offer interview written test experience, including [Java], [operating system], [computer network], [design mode], [data structure and algorithm], [Dacheng face by], [database] look forward to you join!!

1. Computer network —- Three times shake hands four times wave hands

2. Dream come true —– Project self-introduction

Here are the design patterns you asked for

4. Shocked! Check out this programmer interview manual!!

5. Teach you the interview “Profile” word for word

6. Nearly 30 interviews shared