Original article link
Translator:Shen Yiyang
Equals
When a field in an object can be null, it is very painful to implement the object. Equals method, because they have to be checked separately for null. UseObjects. EqualIt helps you perform null-sensitive equals judgment to avoid throwing nullpointerexception. For example:
Objects.equal("a", "a"); // returns trueObjects.equal(null, "a"); // returns falseObjects.equal("a", null); // returns falseObjects.equal(null, null); // returns true
Note: The objects class introduced by JDK 7 provides the same method.Objects. equals.
Hashcode
It should be easier to use all fields of an object as the hash operation. Guava'sObjects. hashcode (object ...)A reasonable and sequence-sensitive hash value is calculated for the input field sequence. You can use objects. hashcode (field1, field2 ,..., Fieldn) instead of manually calculating the hash value.
Note: The objects class introduced by JDK 7 provides the same method.Objects. Hash (object ...)
Tostring
A good tostring method is invaluable during debugging, but it is sometimes painful to write the tostring method. Using objects. tostringhelper, you can easily write useful tostring methods. For example:
// Returns "ClassName{x=1}"Objects.toStringHelper(this).add("x", 1).toString();// Returns "MyObject{x=1}"Objects.toStringHelper("MyObject").add("x", 1).toString();
Compare/compareto
Implementing a comparator [comparator], or directly implementing the comparable interface sometimes cannot afford to hurt. Consider this situation:
class Person implements Comparable<Person> { private String lastName; private String firstName; private int zipCode; public int compareTo(Person other) { int cmp = lastName.compareTo(other.lastName); if (cmp != 0) { return cmp; } cmp = firstName.compareTo(other.firstName); if (cmp != 0) { return cmp; } return Integer.compare(zipCode, other.zipCode); }}
This part of the code is too trivial, so it is easy to mess up and difficult to debug. We should be able to make this code more elegant. For this reason, guava providesComparisonchain.
Comparisonchain executes a lazy comparison: it performs a comparison operation until a non-zero result is found, and the comparison input after that will be ignored.
public int compareTo(Foo that) { return ComparisonChain.start() .compare(this.aString, that.aString) .compare(this.anInt, that.anInt) .compare(this.anEnum, that.anEnum, Ordering.natural().nullsLast()) .result();}
This fluent interface style is more readable, less likely to produce error code, and can avoid unnecessary work. More guava sequencer tools can be found in the next section.
Original article, reprinted Please note:Self-Concurrent Programming Network-ifeve.comLink:[Google guava] 1.3-Common Object Methods
[Google guava] 1.3-Common Object Methods