Guava is an extended project of Google's java1.6-based class library collection, including collections, caching, primitives support, concurrency libraries, common Annotati ONS, string processing, I/O, and so on. These high-quality APIs can make your Java code more elegant and concise, making your work easier and more enjoyable. Let's start the elegant Java programming learning journey!
Project related information:
Official homepage: http://code.google.com/p/guava-libraries
Official Download: http://code.google.com/p/guava-libraries/downloads/list
Official Document: Http://docs.guava-libraries.googlecode.com/git/javadoc
Http://www.ostools.net/apidocs/apidoc?api=guava
A simple description of the source package:
Com.google.common.annotations: Common annotation type.
Com.google.common.base: Basic tool class libraries and interfaces.
Com.google.common.cache: Caching toolkit, a very easy-to-use and powerful in-JVM cache.
Com.google.common.collect: A collection interface with generics extension and implementation, as well as tool classes, where you'll find lots of fun collections.
Com.google.common.eventbus: Publish a subscription-style event bus.
Com.google.common.hash: Hash toolkit.
COM.GOOGLE.COMMON.IO:I/O Toolkit.
Com.google.common.math: Primitive arithmetic type and extra large number of arithmetic toolkit.
Com.google.common.net: Network toolkit.
Com.google.common.primitives: Eight static kits of primitive types and unsigned types.
Com.google.common.reflect: Reflection Kit.
Com.google.common.util.concurrent: Multithreading toolkit.
Class Library User manual:
I. Basic TOOLS class: Make using the Java language more enjoyable.
1. The use and avoidance of null:null language ambiguity can create puzzling errors, which he always makes people uncomfortable. Many guava tool classes reject or fail directly when they encounter NULL, rather than accepting them silently.
2. Prerequisites: It is easier to test your approach with preconditions.
3. Common Object methods: Simplified implementation of object common methods, such as Hashcode () and toString ().
4. Sort: Guava powerful "fluent Comparator" comparator, providing multi-keyword sorting.
5. Throwable class: Simplifies exception checking and error propagation.
Two. Collection class: The Collection Class library is an extension of the JDK collection class guava, which is the most complete and well-known part of the Guava project.
1. Immutable Collections (Immutable collection): Defensive programming, non-modifiable collections, and increased efficiency.
2. New collection types (collection type): JDK collections does not have some collection types, mainly: Multisets,multimaps,tables, bidirectional maps, etc.
3. Powerful collection utilities (powerful Collection tool Class): Common operations Tool classes not included in Java.util.Collections
4. Extension Utilities (Extension tool Class): Add an adorner to the Collection object? Implement iterators? We can use these methods more easily.
Three. Cache: local cache, easy to operate cache objects, and support a variety of cache failure behavior patterns.
Four. Functional idioms (functional): Concise, guava implements the functional programming of Java, which can significantly simplify the code.
Five. Concurrency (concurrency): powerful, simple abstraction that makes it easier to implement simple and correct concurrency code.
1. Listenablefuture (Can monitor the future): Futures, callback for asynchronous completion.
2. Service: Controls the start and shutdown of events, and manages complex state logic for you.
Six. Strings: A very useful string tool class: Provides splitting,joining, padding and other operations.
Seven. Primitives: extends operations that are not provided in the JDK to native types (such as int, char, and so on), including some types of unsigned variables.
Eight. Ranges:guava a powerful API that provides range handling for comparable types, including continuous and discrete scenarios.
Nine. I/O: simplifies I/O operations, especially for I/O streams and files, for Java 5 and 6.
10. Hashing: Provides a more complex hashing method than Object.hashcode (), providing Bloom filters.
Eleven. Eventbus: Component communication based on the publish-subscribe pattern, but does not need to be explicitly registered in the delegate object.
Twelve. Math: Optimized Math tool class, fully tested.
13. Reflection:guava's Java reflection mechanism tool class. 、
Optional elegant use of NULL
Before we learn and use Guava's optional, we need to look at NULL in Java. Because, only we deeply understand the knowledge of NULL, we can more in-depth understanding of guava optional design and use of elegance and simplicity.
Null represents an Indeterminate object:
In Java, NULL is a keyword used to identify an indeterminate object. Therefore, you can assign null to a reference-type variable, but you cannot assign null to a primitive type variable.
In Java, the use of variables follows a principle: they are defined and initialized before they can be used. For example, in the following code, we cannot define an int age and then print the value of age without assigning the value to age. This pair is also applicable for reference type variables (String name also applies) and is prompted for initialization at compile time.
public Class Nulltest {public static void testnull () {int age; System. out . println ( "User age:" +age); long money; Money=10 L; System. out . println ( "user Money" +money); String name; System. out . println ( "user name:" +name); }}
In Java, Java assigns a value to a variable by default: When you define a variable, if you do not assign a value to the variable after it is defined, Java will automatically assign a value to the variable at run time. The assignment principle is an automatic assignment of integers of type int, byte, short, long to 0, a float with a decimal point, a double to automatically assign a value of 0.0,boolean to false, and an automatic assignment of NULL for other reference type variables. The code above changes to run code as follows:
publicclass NullTest { publicstaticvoidtestNull(){ int0; System.out.println("user Age:"+age); long money; money=10L; System.out.println("user money"+money); null; System.out.println("user name:"+name); }}
Null is not itself an object, nor is it an instance of Objcet:
Null is just a keyword used to identify an indeterminate object that is neither an object nor an instance of an Objcet object. Here we determine by code that NULL is not an object instance:
public Class Nulltest {public static void main (string[] args) {testnullobject (); } public static void testnullobject () {if (null instanceof java.lang.Object) {system. Out . println ( "null belongs to Java.lang.Object type" ); } else {system. Out . println (); } }}
Run the above code, output: null is not part of the Java.lang.Object type, visible, the null object is not an instance of the object.
Use of NULL objects:
1. Common usage Scenarios:
Sometimes, we define a reference type variable that, at the beginning, cannot give a definite value, but does not specify a value, and the program may initialize the value in a try statement block. At this point, we will use the variables below the error. At this point, you can assign a null value to the variable before the problem is resolved. For example:
nulltry { conn = DriverManager.getConnection("url""user""password"catchString catalog = conn.getCatalog();
2. Container type and null:
List: Allows repeating elements and can include any number of NULL.
Set: Duplicate elements are not allowed and a maximum of one null can be added. The
Map:map key can join a maximum of one null,value field without restrictions.
Array: An array of primitive types that, when defined, is automatically given a value by the Java runtime if no initial value is given. An array of reference types, not given an initial value, all element values are null.
Other effects of 3.null
1>, determining whether a reference type data is null. Use = = to judge.
2>, frees memory, and makes a non-null reference-type variable point to null. This way the object is no longer applied by any object. Wait for the JVM garbage collection mechanism to recycle.
4.null Usage Recommendations:
1>. Use null as the value of the key value in set or map, and don't use it that way. Obviously, in the query operation of set and map, NULL is used as a special example to make the query result more understandable.
2>. In map contains key value pairs where value is a null value, you should move the key-value pair out of the map and use a separate set to contain all null or non-null keys. It is easy to confuse whether a map contains a key with value null, or if there is no such key-value pair in the map. The best way to do this is to separate this type of key value, and think about what a key value is NULL for your program to mean in the final analysis.
3>. Use null in the list, and the data for this list is sparse, perhaps you'd better use a map
import com.google.common. Base . Optional; public class optionaltest {public void testoptional () throws Exception {optional<integer> possible=optional.of (6 ); if (Possible.ispresent ()) {System. out . println ( "possible isPresent:" + Possible.ispresent ()); System. out . println ( "possible value:" +possible.get ()); } } }
For these reasons, the guava library has designed optional to solve the problem of NULL. Many guava tools are designed to continue running by default with null values if there is an immediate error with a null value instead of as long as the context accepts processing null values. Furthermore, guava provides tools such as optional that allow you to use NULL when you have to use null values and help you avoid using null directly.
The most common value of optional is that, for example, if a method returns a data type, call the code of the method to do the next action based on the return value of the method, if the method can return a null value to indicate success, or fail, it seems to be ambiguous here. So using optional as the return value, the subsequent code can use Ispresent () to determine whether the expected value is returned (originally expected to return null or return is NOT NULL, its meaning is not clear), and can be used to obtain the actual return value.
1. Common static methods:
Optional.of (T): Gets an Optional object that contains a non-null instance of the T data type and, if T=null, an error immediately.
Optional.absent (): Gets a Optional object with a null value inside it
Optional.fromnullable (t): Converts an instance of T to a Optional object, the instance of T can be either empty or null [Optional.fromnullable (NULL), and optional.absent () equivalent.
Importcom. Google. Common. Base. Optional;public class Optionaltest {@Test public void testoptional () throws Exception {optional<integer> poss Ible=optional. of(6);Optional<integer> absentopt=optional. Absent();Optional<integer> nullableopt=optional. Fromnullable(NULL);Optional<integer> nonullableopt=optional. Fromnullable(Ten);if (possible. IsPresent()) {System. out. println("Possible isPresent:"+possible. IsPresent());System. out. println("Possible value:"+possible. Get());} if (absentopt. IsPresent()) {System. out. println("absentopt isPresent:"+absentopt. IsPresent()); ;} if (nullableopt. IsPresent()) {System. out. println("fromnullableopt isPresent:"+nullableopt. IsPresent()); ;} if (nonullableopt. IsPresent()) {System. out. println("nonullableopt isPresent:"+nonullableopt. IsPresent()); ;} } }
2. Example method:
1>. Boolean isPresent (): Returns True if Optional contains a T instance that is not NULL, or False if the T instance is null
2>. T get (): Returns the t instance contained by optional, which must not be empty; otherwise, calling get () on a optional instance that contains null throws a IllegalStateException exception
3>. T or (t): If the optional instance contains the same instance of the incoming T, returns the t instance contained in optional, otherwise returns the input T instance as the default value
4>. T Ornull (): Returns the non-empty T instance contained in the optional instance, returns NULL if the optional contains a null value, and the inverse operation is fromnullable ()
5>. Set AsSet (): Returns a non-modifiable set that contains all non-empty instances of t that are contained in the optional instance, and in which each T instance is a single state, and if there is no instance of T in the optional that is not empty, The returned will be an empty, non-modifiable set.
Import Java.util.set;import Com.google.common.Base. Optional; Public classoptionaltest { Public void Testmethodreturn() {optional<long>value= Method ();if(value. isPresent () = =true) {System. out. println ("Get return value:"+value.Get()); }Else{System. out. println ("Get return value:"+value. or (- AL)); } System. out. println ("Get return value ornull:"+value. Ornull ()); optional<long> valuenonull = Methodnonull ();if(valuenonull.ispresent () = =true) {set<long>Set=valuenonull.asset (); System. out. println ("Get the size of the return value set:"+Set. Size ()); System. out. println ("Get return value:"+ Valuenonull.Get()); }Else{System. out. println ("Get return value:"+ valuenonull.or (- AL)); } System. out. println ("Get return value ornull:"+ Valuenonull.ornull ()); }PrivateOptional<long>Method() {returnOptional.fromnullable (NULL); }PrivateOptional<long>Methodnonull() {returnOptional.fromnullable ( theL); }}
Optional in addition to the name of the null value brought about by the code to improve the readability of the greatest benefit is that optional is a fool-style. The use of optional objects forces you to think positively about a situation where if you want your program to return a null value, this null value represents what the meaning is, because you want to get the return value, which must be obtained from within the optional object, so you must think so. But simply using a null value can easily forget to think about what the code is meant to say, although FindBugs has some help, but we still don't think it's working as hard as possible to help programmers think about the meaning of the null value representation.
This kind of thinking is especially relevant when you return certain values that exist or do not exist. Like everyone else, you'll probably forget the way someone wrote it. Method (A, A, a, b) may return a null value, as if you were to write an implementation of method (A, A, b), and you may also forget that the input parameter A can also be null. If the optional object is returned, for the caller, it is possible to forget how to measure null for what it means, because they always have to get the true return value from the optional object.
java-Class Library-guava