In Java, the Object class is the parent class of all classes. There are several methods that require override, such as equals, hashCode, and toString. Every time you write these methods, you have to make a lot of repetitive judgments. Many class libraries provide tool classes to override these methods. Guava also provides similar methods. Let's take a look at the simple use of these methods in Guava.
Equals method:
Equals is a method that often needs to be overwritten. You can view the equals method comments of the Object. equals has the following requirements:
1. Self-defense reflexive:Any non-null reference x, x. equals (x) returns true;
2. symmetric Ric:Any non-null reference x and y, x. equals (y) returns true if and only if y. equals (x) returns true;
3. transmission:Any non-null references x and y. If x. equals (y) returns true and y. equals (z) returns true, x. equals (z) returns true;
4. consistent:Two non-null references x and y, x. multiple calls of equals (y) should have consistent results (the precondition is that the information of x and y used for comparison is not modified between multiple comparisons );
5. For all non-null values x, x. equals (null), false is returned.. (If you want to use null. equals (x), NullPointerException will be reported ).
When some values in the class to be overwritten may be null, a lot of null judgment and branch processing are required. Using Guava's Objects. equal method can avoid this problem, making it easier to overwrite the equals method, and it is highly readable, concise, and elegant.
"a", "a", "a""a", , Person("peida",23), Person("peida",23= Person("peida",23 .name =.age =
Running output:
HashCode method:
After overwriting the equals () method, you must also override the hashCode () method, and vice versa. This method returns an integer value (hash code value). If the two objects are judged to be equal by the equals () method, they should have the same hash code. The hashCode () method of the Object class returns different values for different objects. The hashCode value of the Object class represents the Object address.
The general contract of hashCode (the conditions to be met) is as follows:
1. During a Java application execution, if the information of the object used for equals comparison is not modified, the same object must return the same integer value when calling the hashCode () method multiple times. In multiple executions of an application, this value does not need to be consistent, that is, each execution maintains its own different values.
2. If equals () determines that two objects are equal, their hashCode () method should return the same value.
3. It is not mandatory that if equals () judges that two objects are not equal, then their hashCode () method should return different values. That is, if two objects are compared using the equals () method, false is returned. Their hashCode can be the same or different. However, it should be realized that generating two different hashcodes for two unequal objects can improve the performance of the hash table.
Writing a hashCode is not difficult, but Guava provides us with a simpler method-Objects. hashCode (Object ...), this is a variable parameter method. The parameter list can be any number, so you can use Objects like this. hashCode (field1, field2 ,..., fieldn ). It is very convenient and concise.
"a""a""a","b""b","a""a","b","c"= Person("peida",23 .name =.age =
128406640961261451931325619313256
ToString () method:
Because each class inherits from the Object directly or indirectly, each class has a toString () method. This method is the most used and overwritten. A good toString method is very important for debugging, but it is really uncomfortable to write. Guava also provides the toString () method.
).add("x", 1).add("x", 1= Person("peida",23= Objects.toStringHelper(Person."name""age" .name =.age =ObjectTest{x=1=1=peida, age=23}
Compare/compareTo method:
CompareTo:The compareTo (Object o) method is java. lang. methods In the Comparable <T> interface. To sort objects of a class, this class must implement the Comparable <T> interface. The public int compareTo (T o) method must be rewritten. Java stipulates that if a and B are two objects. when compareTo (B)> 0, a is greater than B,. compareTo (B) <0, a <B, that is, the rule that specifies the object comparison size;
Compare:The compare (Object o1, Object o2) method is java. util. in the Comparator <T> interface method, the Comparator mainly determines the object size based on the object size and relationship rules defined by compareTo.
The General Convention of the compareTo method is similar to equals: This object is compared with the specified object. If this object is smaller than, equal to, or greater than the specified object, the return value is positive, zero, or positive. If the specified object type cannot be compared with the current object, ClassCastException is run.
Symmetry:The implementer must ensure that all x and y have sgn (x. compareTo (y) =-sgn (y. compareTo (x )). This also implies that x. compareTo (y) throws an exception only when y. compareTo (x) throws an exception.
Transmission:The implementer must ensure that the analogy is passed. If x. compareTo (y)> 0 and y. compareTo (z)> 0, x. compareTo (z)> 0. The implementer must ensure that x. compareTo (y) = 0 implies that all z has (x. compareTo (z) = (y. compareTo (z )).
Although not mandatory, it is strongly recommended that (x. compareTo (y) = 0) = (x. equals (y )).In general, if any class implementing Comparable violates this convention, it should be clear. It is recommended that: "NOTE: This class has a natural order, but it is inconsistent with equals ".
The first article states that if two matching objects are reversed, the following situation occurs: if the first object is smaller than the second object, the second object must be greater than the first object; if the first object is equal to the second object, the second object must be equal to the first object. If the first object is greater than the second object, the second object is smaller than the first object.
Article 2 states that if the first object is greater than the second object and the second object is greater than the third object, the first object is greater than the third object.
Article 3 points out that for two commensurate objects, they should have the same results as any other object.
One of the three conventions is that the equivalence test of the compareTo method must meet the same constraints as that of the equals method: Self-inversion, symmetry, and transmission. So there are also similar constraints: you cannot extend a class that can be instantiated and add new value components, and guarantee the compareTo conventions, unless you are willing to give up the advantages of object-oriented abstraction. You can use the same preventive measure as equals: If you want to add a value component to the class implementing the Comparable interface, do not extend it; you should write an irrelevant class, this includes instances of the first class. Then provide a view method to return the instance. In this way, you can implement any compareTo method on the second class, and allow the customer to regard the second class as an instance of the first class when necessary.
The last section of the compareTo convention is a strong recommendation rather than a true convention, that is, the equivalence test of the compareTo method must be the same as that of the equals method. If this clause is followed, the order in which the compareTo method is applied is the same as that in equals. Otherwise, it is called that the order is different from that in equals. Of course, the compareTo method that is inconsistent with equals can still work. However, if an ordered set contains elements of this class, this Set may not comply with the general conventions of the response Set interface (Collection, Set, Map. This is because the general conventions of these interfaces are based on the equals method, but the ordered set uses compareTo instead of equals for execution.
The following describes how to implement the compareTo method of a class:
= Person("peida",23= Person("aida",25= Person("aida",25= Person("aida",26= Person("peida",26 Person Comparable<Person> .name =.age = cmpName = (cmpName != 0(age> 1 (age< -1 0
// ========= Output ==================
150-1-11
In the above method, the Code does not look very elegant. If there are many entity attributes and rich data types, the code will be poorly readable. In guava, A Comparative tool function is provided for all original types to avoid this problem. For example, you can use. compare (). Using the compare of the original guava type, we can simplify the above method and implement it as follows:
PersonComparator Comparator<Person> result = (result != 0
The above code looks a little simpler, but it is still not so elegant and simple. For this, guava has a pretty smart solution that provides ComparisonChain:
Student Comparable<Student> age,.name =.age =.score= StudentComparator Comparator<Student>
ComparisonChain is a lazy comparison process. When the comparison result is 0, that is, when the comparison result is equal, the comparison will continue. If the comparison result is not 0, the subsequent comparison will be ignored. The implementation and To of ComparisonChain greatly improves code readability and performance.
Here is a comprehensive application example:
= Student("peida",23,80= Student("aida",23,36= Student("jerry",24,90= Student("peida",23,80"==========equals===========""==========hashCode===========""==========toString===========""==========compareTo===========" Student Comparable<Student> age,.name =.age =.score= (obj =&&&& Objects.toStringHelper( StudentComparator Comparator<Student> ==========equals=====================hashCode===========-99199861792809683-991998617-1163491205==========toString===========23, 8023, 3624, 9023, 80==========compareTo===========111-1