# 官方说明文档

返回开源:Google-->Guava

Guava项目包含我们在基于Java的项目中依赖的几个Google核心库:集合,缓存,基元支持,并发库,通用注释,字符串处理,I /O等。 Google员工每天都会在生产服务中使用这些工具。
The Guava project contains several of Google's core libraries that we rely on in our Java-based projects: collections, caching, primitives support, concurrency libraries, common annotations, string processing, I/O, and so forth. Each of these tools really do get used every day by Googlers, in production services.

但是,通过Javadoc拖网并不总是学习如何最好地利用图书馆的最有效方式。在这里,我们尝试为番石榴的一些最流行和最强大的功能提供可读和愉快的解释。
But trawling through Javadoc isn't always the most effective way to learn how to make best use of a library. Here, we try to provide readable and pleasant explanations of some of the most popular and most powerful features of Guava.

这个维基是一项正在进行的工作,其中一部分可能仍在建设中。
This wiki is a work in progress, and parts of it may still be under construction.

back | API-DOC

# com.google.common.annotations

Common annotation types.

Annotation Type Description
Beta Signifies that a public API (public class, method or field) is subject to incompatible changes, or even removal, in a future release.
GwtCompatible 在类型上存在此注释表示该类型可以与Google Web Toolkit(GWT)一起使用。The presence of this annotation on a type indicates that the type may be used with the Google Web Toolkit (GWT).
GwtIncompatible API上存在此注释表明该方法可能未与Google Web Toolkit(GWT)一起使用。The presence of this annotation on an API indicates that the method may not be used with the Google Web Toolkit (GWT).
VisibleForTesting 注释一个程序元素,该元素只存在于测试代码中,或者比其他方面更加可见。Annotates a program element that exists, or is more widely visible than otherwise necessary, only for use in test code.

# Interface Summary

Interface Description
FinalizableReference 由引用实现,这些引用具有在对象的垃圾收集之后运行的代码。Implemented by references that have code to run after garbage collection of their referents.
Function<F,T> Legacy version of java.util.function.Function.
Predicate<T> Legacy version of java.util.function.Predicate.
Supplier<T> Legacy version of java.util.function.Supplier.

# Class Summary

Class Description
Ascii 与ASCII字符有关的静态方法(值范围为0x00到0x7F的静态方法),以及包含此类字符的字符串。Static methods pertaining to ASCII characters (those in the range of values 0x00 through 0x7F), and to strings containing such characters.
CharMatcher 确定任何Java char值的true或false值,就像Predicate对任何Object所做的那样。Determines a true or false value for any Java char value, just as Predicate does for any Object.
Charsets 包含六个标准Charset实例的常量定义,保证所有Java平台实现都支持这些实例。Contains constant definitions for the six standard Charset instances, which are guaranteed to be supported by all Java platform implementations.
Converter<A,B> 从A到B的函数,具有从B到A的相关反函数;用于在相同信息的不同表示之间来回转换。A function from A to B with an associated reverse function from B to A; used for converting back and forth between different representations of the same information.
Defaults 此类为JLS定义的所有Java类型提供默认值。This class provides default values for all Java types, as defined by the JLS.
Enums Utility methods for working with Enum instances.
Equivalence<T> 用于确定两个实例是否被认为是等效的策略,以及以与该等价一致的方式计算哈希码的策略。 A strategy for determining whether two instances are considered equivalent, and for computing hash codes in a manner consistent with that equivalence.
Equivalence.Wrapper<T> 包装一个对象,使Equivalence.Wrapper.equals(Object)和Equivalence.Wrapper.hashCode()委托为Equivalence。Wraps an object so that Equivalence.Wrapper.equals(Object) and Equivalence.Wrapper.hashCode() delegate to an Equivalence.
FinalizablePhantomReference<T> Phantom reference with a finalizeReferent() method which a background thread invokes after the garbage collector reclaims the referent.
FinalizableReferenceQueue A reference queue with an associated background thread that dequeues references and invokes FinalizableReference.finalizeReferent() on them.
FinalizableSoftReference<T> Soft reference with a finalizeReferent() method which a background thread invokes after the garbage collector reclaims the referent.
FinalizableWeakReference<T> Weak reference with a finalizeReferent() method which a background thread invokes after the garbage collector reclaims the referent.
Functions Static utility methods pertaining to com.google.common.base.Function instances; see that class for information about migrating to java.util.function.
Joiner An object which joins pieces of text (specified as an array, Iterable, varargs or even a Map) with a separator.
Joiner.MapJoiner An object that joins map entries in the same manner as Joiner joins iterables and arrays.
MoreObjects Helper functions that operate on any Object, and are not already provided in Objects.
MoreObjects.ToStringHelper Support class for MoreObjects.toStringHelper(java.lang.Object).
Objects Helper functions that can operate on any Object.
Optional<T> An immutable object that may contain a non-null reference to another object.
Preconditions Static convenience methods that help a method or constructor check whether it was invoked correctly (that is, whether its preconditions were met).
Predicates Static utility methods pertaining to Predicate instances.
Splitter Extracts non-overlapping substrings from an input string, typically by recognizing appearances of a separator sequence.
Splitter.MapSplitter An object that splits strings into maps as Splitter splits iterables and lists.
Stopwatch An object that measures elapsed time in nanoseconds.
Strings Static utility methods pertaining to String or CharSequence instances.
Suppliers Useful suppliers.
Throwables Static utility methods pertaining to instances of Throwable.
Ticker A time source; returns a time value representing the number of nanoseconds elapsed since some fixed but arbitrary point in time.
Utf8 Low-level, high-performance utility methods related to the UTF-8 character encoding.
Verify Static convenience methods that serve the same purpose as Java language assertions, except that they are always enabled.

# Enum Summary

Enum Description
CaseFormat Utility class for converting between various ASCII case formats.
StandardSystemProperty Represents a standard system property.

# Exception Summary

Exception Description
VerifyException Exception thrown upon the failure of a verification check, including those performed by the convenience methods of the Verify class.

# Ascii

java.lang.Object
com.google.common.base.Ascii

@GwtCompatible
public final class Ascii
extends Object
1
2
3

# Basic utilities

back

Make using the Java language more pleasant.

# Using and avoiding null

"Null sucks." -Doug Lea
"I call it my billion-dollar mistake." - Sir C. A. R. Hoare, on his invention of the null reference

null可能不明确,可能导致混淆错误,有时候只是简单的不愉快。许多Guava实用程序拒绝并且在空值上快速失败,而不是盲目地接受它们
null can be ambiguous, can cause confusing errors, and is sometimes just plain unpleasant. Many Guava utilities reject and fail fast on nulls, rather than accepting them blindly.

Careless use of null can cause a staggering variety of bugs. Studying the Google code base, we found that something like 95% of collections weren't supposed to have any null values in them, and having those fail fast rather than silently accept null would have been helpful to developers.

Additionally, null is unpleasantly ambiguous. It's rarely obvious what a null return value is supposed to mean -- for example, Map.get(key) can return null either because the value in the map is null, or the value is not in the map. Null can mean failure, can mean success, can mean almost anything. Using something other than null makes your meaning clear.

That said, there are times when null is the right and correct thing to use. null is cheap, in terms of memory and speed, and it's unavoidable in object arrays. But in application code, as opposed to libraries, it is a major source of confusion, difficult and weird bugs, and unpleasant ambiguities -- e.g. when Map.get returns null, it can mean the value was absent, or the value was present and null. Most critically, null gives no indication what a null value means.

For these reasons, many of Guava's utilities are designed to fail fast in the presence of null rather than allow nulls to be used, so long as there is a null-friendly workaround available. Additionally, Guava provides a number of facilities both to make using null easier, when you must, and to help you avoid using null.

# 具体案例

back

Specific Cases

如果您尝试在Set中使用空值或在Map中使用键 -请不要;如果在查找操作期间显式特殊情况为null,则更清楚(不太令人惊讶)。
If you're trying to use null values in a Set or as a key in a Map -- don't; it's clearer (less surprising) if you explicitly special-case null during lookup operations.

如果你想在地图中使用null作为值 -请忽略该条目;保留一组单独的非空键(或空键)。混合Map包含键的条目,值为null的情况以及Map没有键的条目的情况非常容易。将这些密钥分开是更好的,并且当与密钥相关联的值为空时,考虑它对应用程序的意义。
If you want to use null as a value in a Map -- leave out that entry; keep a separate Set of non-null keys (or null keys). It's very easy to mix up the cases where a Map contains an entry for a key, with value null, and the case where the Map has no entry for a key. It's much better just to keep such keys separate, and to think about what it means to your application when the value associated with a key is null.

If you're using nulls in a List -- if the list is sparse, might you rather use a Map<Integer, E>? This might actually be more efficient, and could potentially actually match your application's needs more accurately.

Consider if there is a natural "null object" that can be used. There isn't always. But sometimes. For example, if it's an enum, add a constant to mean whatever you're expecting null to mean here. For example, java.math.RoundingMode has an UNNECESSARY value to indicate "do no rounding, and throw an exception if rounding would be necessary."

If you really need null values, and you're having problems with a null-hostile collection implementations, use a different implementation. For example, use Collections.unmodifiableList(Lists.newArrayList()) instead of ImmutableList.

# Optional

back

程序员使用null的许多情况都表明存在某种缺失:可能存在一个值,也就是没有,或者找不到一个。例如,当没有找到键的值时,Map.get返回null。
Many of the cases where programmers use null is to indicate some sort of absence: perhaps where there might have been a value, there is none, or one could not be found. For example, Map.get returns null when no value is found for a key.

Optional<T> is a way of replacing a nullable T reference with a non-null value. An Optional may either contain a non-null T reference (in which case we say the reference is "present"), or it may contain nothing (in which case we say the reference is "absent"). It is never said to "contain null."

Optional<Integer> possible = Optional.of(5);
possible.isPresent(); // returns true
possible.get(); // returns 5
1
2
3

Optional is not intended as a direct analogue of any existing "option" or "maybe" construct from other programming environments, though it may bear some similarities.

We list some of the most common Optional operations here.

# Making an Optional

Each of these are static methods on Optional.

Method Description
Optional.of(T) Make an Optional containing the given non-null value, or fail fast on null.
Optional.absent() Return an absent Optional of some type.
Optional.fromNullable(T) Turn the given possibly-null reference into an Optional, treating non-null as present and null as absent.