How to use the toString method in Java?

前端 未结 13 903
说谎
说谎 2020-11-21 06:26

Can anybody explain to me the concept of the toString() method, defined in the Object class? How is it used, and what is its purpose?

13条回答
  •  时光说笑
    2020-11-21 07:15

    toString() returns a string/textual representation of the object. Commonly used for diagnostic purposes like debugging, logging etc., the toString() method is used to read meaningful details about the object.

    It is automatically invoked when the object is passed to println, print, printf, String.format(), assert or the string concatenation operator.

    The default implementation of toString() in class Object returns a string consisting of the class name of this object followed by @ sign and the unsigned hexadecimal representation of the hash code of this object using the following logic,

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

    For example, the following

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

    prints

    Bourne's current location - Coordinates@addbf1 //concise, but not really useful to the reader
    

    Now, overriding toString() in the Coordinates class as below,

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

    results in

    Bourne's current location - (1.0, 2.0) //concise and informative
    

    The usefulness of overriding toString() becomes even more when the method is invoked on collections containing references to these objects. For example, the following

    public static void main(String[] args) {
        Coordinates bourneLocation = new Coordinates(90, 0);
        Coordinates bondLocation = new Coordinates(45, 90);
        Map locations = new HashMap();
        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)}
    

    instead of this,

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

    Few implementation pointers,

    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.Math. The case of override being not required is pretty intuitive; almost always you would know.
    2. The string returned should be concise and informative, ideally self-explanatory.
    3. At least, the fields used to establish equivalence between two different objects i.e. the fields used in the equals() method implementation should be spit out by the toString() method.
    4. Provide accessors/getters for all of the instance fields that are contained in the string returned. For example, in the Coordinates class,

      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.

提交回复
热议问题