Java record-45-List's toString Method
When using a set, it is customary to traverse every element in a loop. If you want to know the information of each element in the Set, do you have to traverse each element cyclically? For example, when printing log information, some sets, such as List, need to be recorded. Generally, the set is traversed cyclically and the information of each element in the set is recorded. Is there a simpler way? Generally, the toString () method is used to display object information. What information does the toString () method of the set display? The following describes how to use a simple program:
Public class ArrayListTest2 {public static void main (String [] args) {ArrayList list = new ArrayList (); list. add (new Point (1, 2); list. add (new Point (3, 4); for (int I = 0; I <list. size (); I ++) {System. out. println (list. get (I);} System. out. println (list); // print list is equivalent to printing its toString () method. // System. out. println (list. toString () ;}} class Point {int x, y; Point (int x, int y) {this. x = x; this. y = y ;}@ Override public String toString () {return "x =" + x + ", y =" + y ;}}
When we do not rewrite the toString () method for the Point class, we execute the above Code and obtain the following print result:
my.arraylist.Point@c17164my.arraylist.Point@1fb8ee3[my.arraylist.Point@c17164, my.arraylist.Point@1fb8ee3]
However, when we rewrite the toString () method for the Point class, we get the following different results:
x=1, y=2x=3, y=4[x=1, y=2, x=3, y=4]
I believe that through the comparison above, we can clearly know what the toString () method of List has done: the toString () of List () method calls the toString () method of each element it stores. Conclusion: when we implement the toString () method of the objects to be recorded and store them in the set, we want to print the record information, you can directly print records of this set. The set will continue printing records for each element.