One 、 Comparison of objects
Before, if it was a comparison of two values “==”, If it's a string comparison, it's usually used “equals()" Method , The method is String Class itself , How can we compare the objects of our custom class , If you use “==” Comparison compares the address information of two objects , But we normally think that all attribute values of two objects are equal, and two objects are equal .
DEMO: Compare the objects of a custom class
The above can realize object comparison , But it's implemented in the main method , General requirements The logical business code should be avoided as far as possible , The main method is a client , It's better to leave the process of comparison to Dept Class to complete .
DEMO: stay Dept Methods are defined in to realize the comparison of objects
The above code may be compared with the object itself , This kind of code is meaningless , So the code needs to be improved .
DEMO: Prevent the object from comparing itself with itself
There are still problems with the above code , The object that may be compared is an empty object , So there is a null pointer exception , So the code needs to be improved .
DEMO: Prevent comparison of empty objects
1、 The comparison of custom objects is meaningful only when two objects are created by the same class .
2、 When comparing, we should judge whether it is an empty object .
3、 When comparing, we should judge whether the object is compared with ourselves .
There is a complete Java primary , Advanced corresponding learning routes and materials ！ Focus on java Development . Share java Basics 、 Knowledge of principle 、JavaWeb actual combat 、spring Family bucket 、 Design patterns 、 Distributed and interview materials 、 Open source project , Help developers grow ！
Welcome to WeChat official account. ： Code state Lord