Getting started with Google guava

Source: Internet
Author: User
Tags new set google guava

The following documents are organized from the network

1. Introduction to Google guava

Introduction

The guava project contains several core libraries that are widely relied on by Google's Java projects. For example: set [collections], cache [caching], native support [primitives support], concurrent Library [concurrency libraries], General annotation [common annotations], string processing [string processing], I /O and so on. All these tools are applied to product services by Google engineers every day.

Reading javadoc is not necessarily the most effective way to learn these libraries. Here, we hope to use this document to provide a more readable and explanatory description of the most popular and powerful features in guava.

 

Translation format description

  • When a class in guava is referenced for the first time, it is linked to the guava API documentation. For example, optional <t>.
  • When methods in guava and JDK are referenced, they are generally linked to the guava or jdk api documentation, except for JDK methods that are well known. For example: Optional. Of (t), map. Get (key ).
  • The additional description of the document is displayed in italic andTranslator's note:.

Directory

1. Basic tools [basic utilities]

Make Java language more comfortable

1.1 Use and avoid NULL: NULL is ambiguous and can cause confusing errors. Sometimes it is uncomfortable. Many guava tool classes reject null values with quick failure instead of blindly accepting

1.2 Prerequisites: simplify the condition check in the Method

1.3 Common Object Methods: simplify object methods, such as hashcode () and tostring ()

1.4 sorting: Guava's powerful "smooth style comparator"

1.5 throwables: simplifies the propagation and check of exceptions and errors

2. Set [collections]

Guava extends the JDK set, which is the most mature and well-known part of guava.

2.1 immutable set: use an immutable set for defensive programming and performance improvement.

2.2 New set types: multisets, multimaps, tables, bidirectional maps, etc.

2.3 powerful collection tool: Provides collection tools not available in Java. util. Collections

2.4 Extension tool class: it makes it easier to implement and extend the collection class, such as creating a collection decorator or implementing an iterator.

3. cache [caches]

Guava cache: local cache implementation, supporting multiple cache expiration policies

4. Function style [functional idioms]

Guava's functional support can significantly simplify the code, but use it with caution

5. Concurrency [concurrency]

Powerful and simple abstraction, making it easier to write correct concurrent code

5.1 listenablefuture: the future that triggers the callback after completion

5.2 service framework: abstract the services that can be enabled and disabled to help you maintain the service status Logic

6. string processing [Strings]

Very useful string tools, including splitting, joining, filling, and other operations

7. Native type [primitives]

Extends native type operations (such as int and char) not provided by JDK, including some types of unsigned form

8. interval [ranges]

Comparable interval APIs, including continuous and discrete APIs

9. I/O

Simplifies operations on I/O, especially I/O streams and files, for Java 5 and 6

10. Hash

Provides more complex hash implementation than object. hashcode () and bloom filter implementation.

11. Event bus [eventbus]

Publish-subscribe mode for component communication, but the component does not need to be explicitly registered to other components

12. mathematical operations [math]

Optimized and fully tested mathematical tools

13. Reflection [reflection]

Guava's Java reflection mechanism tool class

Chinese reference site: http://ifeve.com/google-guava/

Ii. Guava Study Notes: excellent parameters for preconditions

During daily development, we often perform some data format verification on the input parameters of the method to ensure that the method can be executed according to the normal process. For predictable data errors, we must check and Judge beforehand to avoid program process errors, rather than making sure that the process is correctly executed through error handling, after all, error handling is a resource-consuming method. Under normal circumstances, we need to write methods one by one to determine the parameters. There are a lot of code and the reusability is not high, as shown below:

Import Org. JUnit. test; public class preconditionstest {@ test public void preconditions () throws exception {getperson (8, "peida"); getperson (-9, "peida"); getperson (8, ""); getperson (8, null);} public static void getperson (INT age, string Neme) throws exception {If (age> 0 & Neme! = NULL & Neme. isempty ()! = True) {system. out. println ("A person age:" + age + ", Neme:" + Neme);} else {system. out. println ("Incorrect Parameter input! ");}}}

Note: For parameter verification, we need to add the if statement each time for judgment. Repeated operations will be done multiple times. The getperson method has only two parameters, and the verification rules are not very complex. If the parameters are too complex and the verification rules are complex, the code above will be poorly readable, And the reusability will be far from enough.

The guava Class Library provides a tool class for parameter check-preconditions class, which can greatly simplify the pre-judgment and processing of parameters in our code, let's make it easier and more elegant to verify the input parameters of the method. Let's take a look at the preconditions class usage example:

Methods In preconditions:

  1. checkargument (Boolean ):
Function Description: checks whether Boolean is true. Used as a parameter for checking in a method
The exception type thrown when a failure occurs: illegalargumentexception

  2. checknotnull (t ):
Function Description: checks whether the value is null and returns the value directly;
The exception type thrown when a failure occurs: nullpointerexception

 3. checkstate (Boolean ):
Function Description: checks the status of an object and does not rely on method parameters. For example, iterator can be used to determine whether to call next before removing.
The exception type thrown when a failure occurs: illegalstateexception

 4. checkelementindex (INT index, int size ):
Function Description: checks whether the index is within a valid range of a list, string, or array with a length of size. The range of the index is [0, size) (contains 0 and does not contain size ). You do not need to input list, string, or array directly. You only need to input the size. Returns index.
Exception type thrown when a failure occurs: indexoutofboundsexception


  5. checkpositionindex (INT index, int size ):
Function Description: checks whether the position index is in a list with a length of size, which is a valid range of string or array. The range of the index is [0, size) (contains 0 and does not contain size ). You do not need to input list, string, or array directly. You only need to input the size. Returns index.
Exception type thrown when a failure occurs: indexoutofboundsexception

 6. checkpositionindexes (INT start, int end, int size ):
Function Description: Check whether [start, end) is a list with a length of size, and a valid range subset of string or array. With the error message.
Exception type thrown when a failure occurs: indexoutofboundsexception

A more practical example:

Import Java. util. arraylist; import Java. util. list; import Org. JUnit. test; import COM. google. common. base. preconditions; public class preconditionstest {@ test public void preconditions () throws exception {getpersonbyprecondition (8, "peida"); try {getpersonbyprecondition (-9, "peida ");} catch (exception e) {system. out. println (E. getmessage ();} Try {getpersonbyprecondition (8, "");} catch (exception e) {system. out. println (E. getmessage ();} Try {getpersonbyprecondition (8, null);} catch (exception e) {system. out. println (E. getmessage () ;}list <integer> intlist = new arraylist <integer> (); For (INT I = 0; I <10; I ++) {try {checkstate (intlist, 9); intlist. add (I);} catch (exception e) {system. out. println (E. getmessage () ;}try {checkpositionindex (intlist, 3);} catch (exception e) {system. out. println (E. getmessage ();} Try {checkpositionindex (intlist, 13);} catch (exception e) {system. out. println (E. getmessage ();} Try {checkpositionindexes (intlist, 3,7);} catch (exception e) {system. out. println (E. getmessage ();} Try {checkpositionindexes (intlist, 3,17);} catch (exception e) {system. out. println (E. getmessage ();} Try {checkpositionindexes (intlist, 13, 17);} catch (exception e) {system. out. println (E. getmessage ();} Try {checkelementindex (intlist, 6);} catch (exception e) {system. out. println (E. getmessage ();} Try {checkelementindex (intlist, 16);} catch (exception e) {system. out. println (E. getmessage () ;}} public static void getpersonbyprecondition (INT age, string Neme) throws exception {preconditions. checknotnull (Neme, "Neme is null"); preconditions. checkargument (Neme. length ()> 0, "Neme is \ '"); preconditions. checkargument (age> 0, "age must be greater than 0"); system. out. println ("A person age:" + age + ", Neme:" + Neme);} public static void checkstate (list <integer> intlist, int index) throws exception {// if the expression is true, no exception is thrown. checkstate (intlist. size () <index, "intlist size cannot be greater than" + index);} public static void checkpositionindex (list <integer> intlist, int index) throws exception {preconditions. checkpositionindex (index, intlist. size (), "Index" + index + "is not in list, and list size is:" + intlist. size ();} public static void checkpositionindexes (list <integer> intlist, int start, int end) throws exception {preconditions. checkpositionindexes (START, end, intlist. size ();} public static void checkelementindex (list <integer> intlist, int index) throws exception {preconditions. checkelementindex (index, intlist. size (), "index is" + index + "is not in list, list size is:" + intlist. size ());}}

Output result:

A person age: 8, Neme: peidaage must be greater than 0neme. ''neme is null. intlist size cannot be greater than 9. Index 13 is not in list. list size is 9 (13) must not be greater than size (9) end index (17) must not be greater than size (9) Start index (13) must not be greater than size (9) the index is 16 and is not in list. The list size is 9 (16) must be less than size (9)

 

Guava's preconditions has the following advantages:

After static import, the method is clear and unambiguous. checknotnull can clearly tell you what it is and what exceptions it will throw.
Checknotnull is directly returned after the verification is passed. You can easily write the code: This. Field = checknotnull (field ).
Simple and powerful Variable Parameter 'printf'-style custom error messages.

Reference: http://www.baidu.com/link? Url = BIz5TsQ_MlPY9Jq3_Cbb0qMO75p35BLdZWPc0qyfgOXazg7VrTi365XMMs-exrXAqHzen-M2EzWbuLSeI7Ydl _

 

Getting started with Google guava

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.