Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 11.2k
CommonObjectUtilitiesExplained
When your object fields can be null, implementing Object.equals can be a
pain, because you have to check separately for null. Using Objects.equal
lets you perform equals checks in a null-sensitive way, without risking a
NullPointerException.
Objects.equal("a", "a"); // returns trueObjects.equal(null, "a"); // returns falseObjects.equal("a", null); // returns falseObjects.equal(null, null); // returns trueNowadays, prefer the JDK's equivalent Objects.equals method.
Hashing all the fields of an Object should be simpler. Guava's
Objects.hashCode(Object...) creates a sensible, order-sensitive hash for the
specified sequence of fields. Use Objects.hashCode(field1, field2, ..., fieldn) instead of building the hash by hand.
Nowadays, prefer the JDK's equivalent Objects.hash(Object...).
A good toString method can be invaluable in debugging, but is a pain to write.
Use MoreObjects.toStringHelper() to easily create a useful toString. Some
simple examples include:
// Returns "ClassName{x=1}"MoreObjects.toStringHelper(this)
.add("x", 1)
.toString();
// Returns "MyObject{x=1}"MoreObjects.toStringHelper("MyObject")
.add("x", 1)
.toString();Implementing a Comparator, or implementing the Comparable interface
directly, can be a pain. Consider:
classPersonimplementsComparable<Person> {
privateStringlastName;
privateStringfirstName;
privateintzipCode;
publicintcompareTo(Personother) {
intcmp = lastName.compareTo(other.lastName);
if (cmp != 0) {
returncmp;
}
cmp = firstName.compareTo(other.firstName);
if (cmp != 0) {
returncmp;
}
returnInteger.compare(zipCode, other.zipCode);
}
}This code is easily messed up, tricky to scan for bugs, and unpleasantly verbose. We should be able to do better.
For this purpose, Guava provides ComparisonChain.
ComparisonChain performs a "lazy" comparison: it only performs comparisons
until it finds a nonzero result, after which it ignores further input.
publicintcompareTo(Foothat) {
returnComparisonChain.start()
.compare(this.aString, that.aString)
.compare(this.anInt, that.anInt)
.compare(this.anEnum, that.anEnum, Ordering.natural().nullsLast())
.result();
}This fluent idiom is much more readable, less prone to accidental typos, and
smart enough not to do more work than it must. Additional comparison utilities
can be found in Guava's "fluent Comparator" class Ordering, explained
here.
- Introduction
- Basic Utilities
- Collections
- Graphs
- Caches
- Functional Idioms
- Concurrency
- Strings
- Networking
- Primitives
- Ranges
- I/O
- Hashing
- EventBus
- Math
- Reflection
- Releases
- Tips
- Glossary
- Mailing List
- Stack Overflow
- Android Overview
- Footprint of JDK/Guava data structures