How to use the toString method in Java?

前端 未结 13 907
说谎
说谎 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 06:54

    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.

    0 讨论(0)
  • 2020-11-21 06:55

    The toString() method returns a textual representation of an object. A basic implementation is already included in java.lang.Object and so because all objects inherit from java.lang.Object it is guaranteed that every object in Java has this method.

    Overriding the method is always a good idea, especially when it comes to debugging, because debuggers often show objects by the result of the toString() method. So use a meaningful implementation but use it for technical purposes. The application logic should use getters:

    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()+"]";
      }
    }
    
    0 讨论(0)
  • 2020-11-21 06:55

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

    This is why

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

    works, and by overriding the standard toString() from Object in your own classes, you can make your objects useful in String contexts too.

    (and consider it a black box! Never, ever use the contents for anything else than presenting to a human)

    0 讨论(0)
  • 2020-11-21 06:55
    /**
     * 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();
    }
    
    0 讨论(0)
  • 2020-11-21 06:56

    Use of the String.toString:

    Whenever you require to explore the constructor called value in the String form, you can simply use String.toString... for an example...

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

    ... copy this program into your Eclipse, and run it... you will get the ideas about String.toString...

    0 讨论(0)
  • 2020-11-21 06:56

    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.

    There is no set requirement for what a toString() method should do. By convention, most often it will tell you the name of the class and the value of pertinent data members. More often than not, toString() methods are auto-generated in IDEs.

    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.

    0 讨论(0)
提交回复
热议问题