[Guava Study Notes] Basic Utilities: Null, precondition, Object method, sorting, exception, guava Study Notes
My technical blog is often maliciously crawled and reproduced by rogue websites. Please move to the original article: Workshop.
Null
Guava uses Optional to indicate T-type references that may be null.
Create:Optional. of (T) does not accept nullOptional. fromNullable (T) accepts nullOptional. absent ()
Query:IsPresent ()Get ()Or (T) if it is null, It is TOrNull ()
Others:Objects. firstNonNull (T, T) is used to specify the default value for null. If both are null, NullPointerException is thrown.
EmptyToNull (String ),NullToEmpty (String)
Prerequisites
Usage:
checkArgument(i >= 0, "Argument was %s but expected nonnegative", i);checkArgument(i < j, "Expected i < j, but %s > %s", i, j);
CheckArgument (boolean)CheckNotNull (T)CheckState (boolean)
CheckElementIndex (int index, int size)CheckPositionIndexes (int start, int end, int size)
Inline use:This. field = checkNotNull (field)
Object Method
Objects. equals (a, B) equals that can be nullObjects. hash (Object ...)
ToString ():
// Returns "ClassName{x=1}"Objects.toStringHelper(this).add("x", 1).toString();// Returns "MyObject{x=1}"Objects.toStringHelper("MyObject").add("x", 1).toString();
Compare ():
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();}
Sort
Ordering: Comparator implementation
Structure: natural order of natural ()UsingToString () Lexicographic OrderFrom (Comparator)
Chain call:Reverse ()NullsFirst ()NullsLast ()Lexicographical ()OnResultOf (Function)
Ordering<Foo> ordering = Ordering.natural().nullsFirst().onResultOf(new Function<Foo, String>() { public String apply(Foo foo) { return foo.sortedBy; }});
Set and element:GreatestOf (Iterable iterable, int k)Min (Iterable)Min (E, E ...)
IsOrdered (Iterable)SortedCopy (Iterable)