1. Definition and function of toString method
toString
MethodThe official definition is the string representation of the return object. This sounds simple, but it does not matter. When we need to view the object's information in the form of a string, or output the object's information to logs, consoles, etc.toString
The method comes in great use.
For example, we have onePerson
Class, including name, age and other attributes. If we print this directlyPerson
Object, not rewritetoString
Method, then what you see will be a string of similarPerson@1a2b3c
The string, which is readable is simply zero. But if we rewrittentoString
Method, let it returnName: Zhang San, Age: 20
Such a string is obvious at a glance.
public class Person { private String name; private int age; @Override public String toString() { return "Name: " + name + ", age: " + age; } }
2. What should I pay attention to when rewriting the toString method?
(I) The integrity and simplicity of information
RewritetoString
When we do the method, we needMake sure the returned string contains important information about the object, but it cannot be too verbose. Let users quickly understand the key properties of objects.
For example, in an e-commerce systemOrder
In the class, we may only need to return key information such as order number and total price, without listing the detailed information of each product.
(II) Uniformity of format
To facilitate analysis and reading, try to maintain the uniform format. Fixed delimiters, such as commas, colons, etc., can be used to separate different attributes.
(III) Avoid performance problems
If there are many attributes of an object, or if some attributes are calculated,RewritingtoString
Pay attention to avoid performance issues when doing the method. Consider including only necessary properties, or optimizing time-consuming calculations.
(IV) Thread safety
ifObjects may be accessed in a multi-threaded environment, then rewritetoString
Thread safety issues should be considered when doing the method. For example, you can use synchronization mechanisms or avoidtoString
Modify the state of the object in the method.
(V) Avoid recursive loops
This is a relatively easy issue to be overlooked. If the object's properties contain other objects, and these objects refer to the current object, then rewritetoString
Methods may lead to recursive loops, which will eventually lead to stack overflow errors.
For example,
We have oneA
Class and oneB
kind,A
There is one in the classB
Attributes of types,B
There is another one in the categoryA
Attributes of types.
If we areA
ClassictoString
The method is calledB
ClassictoString
method,
And inB
ClassictoString
The method is called againA
ClassictoString
Methods, then you will fall into a dead loop of infinite recursion.
To avoid this, we cantoString
Restrict recursive calls in the method, such as using a tag to record whether it has been called.toString
Method, or only print part of the information of the object.
public class A { private B b; @Override public String toString() { if (b == null) { return "A@null"; } return "A@" + (); } } public class B { private A a; @Override public String toString() { if (a == null) { return "B@null"; } return "B@" + (); } }
In this example, if we createA
andB
Objects, and let them refer to each other, then invokeA
The object'stoString
Methods will lead to recursive loops.
To avoid this problem, we cantoString
Add a tag to the method, such as:
public class A { private B b; private boolean isToStringCalled = false; @Override public String toString() { if (isToStringCalled) { return "A@..."; } isToStringCalled = true; if (b == null) { return "A@null"; } return "A@" + (); } } public class B { private A a; private boolean isToStringCalled = false; @Override public String toString() { if (isToStringCalled) { return "B@..."; } isToStringCalled = true; if (a == null) { return "B@null"; } return "B@" + (); } }
In this way, whentoString
When the method is called, if it is found that the tag has been set totrue
, returns a simplified string, avoiding recursive loops. (This comparison is similar to avoiding mutex mutex locks)
3. How to call the toString method of the parent class in a custom class?
Sometimes, we rewrittentoString
Method, but also hope to retain the parent classtoString
Method information.
At this time, you can use it()
To call the parent classtoString
method.
For example, we have oneStudent
Class inherits fromPerson
kind,Student
The student number attribute has been added to the class.
RewritingStudent
ClassictoString
When a method, we can first call the parent class’stoString
Method, and then add the information of the student number.
public class Student extends Person { private String studentId; @Override public String toString() { return () + ", Student ID: " + studentId; } }
In this way, when we print aStudent
When using an object, you can see information about the parent class and the child class at the same time.
4. In addition to the Object class, what are the toString methods of the classes are more commonly used?
(I) Collection Class
Collections such asArrayList
、HashMap
Wait, theirtoString
The method returns a string representation of elements in the collection. This is very convenient when debugging and viewing collection content.
ArrayList<String> list = new ArrayList<>(); ("a"); ("b"); ("c"); (()); // Output: [a, b, c]
(II) Date category
Date categories such asDate
、LocalDate
Wait, theirtoString
The method returns a string representation of the date.
Date date = new Date(); (()); // The output is similar: Fri Apr 05 10:30:45 GMT 2024 LocalDate localDate = (); (()); // The output is similar: 2024-04-05
(III) Numerical packaging
Numerical packaging categories such asInteger
、Double
Wait, theirtoString
The method returns a string representation of the numeric value.
Integer num = 123; (()); // Output: 123 Double d = 3.14; (()); // Output: 3.14
5. Application scenarios of toString method
(I) Debugging
During the debugging process,toString
Methods can help us quickly view the status of objects. For example, in the IDE debugger, when we look at an object, the debugger will usually call the object'stoString
Method to display object information.
(II) Logging
In logging, we often need to record the information of the object as a string. At this time,toString
The method comes in great use.
Logger logger = (); Person person = new Person("Zhang San", 20); (());
(III) User interface display
In the user interface, sometimes it is necessary to display the object information to the user as a string. For example, displaying the user's personal information in a table, you can use ittoString
Method to get the string representation of the user object.
6. Summary
toString
Although the method seems simple, it has a wide range of applications in Java programming. RewritetoString
When doing the method, pay attention to the integrity, simplicity, uniformity of the format, and avoiding performance problems and recursive loops. In a custom class, you can use()
To call the parent classtoString
Method to retain information of the parent class. Apart fromObject
In addition to the class, collection class, date class, numerical packaging class, etc.toString
The method is also commonly used. I hope this blog can help you better understand and use ittoString
Method, go further and further on the road of Java programming!
This is the article about the in-depth analysis and application scenarios of the toString method in Java. For more detailed explanations of the Java toString method, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!