Google Guava新手教程

     以下资料整理自网络

一、Google Guava入门介绍

引言

Guavaproject包括了若干被Google的 Java项目广泛依赖 的核心库,比如:集合 [collections] 、缓存 [caching] 、原生类型支持 [primitives support] 、并发库 [concurrency libraries] 、通用注解 [common annotations] 、字符串处理 [string processing] 、I/O 等等。 全部这些工具每天都在被Google的project师应用在产品服务中。

查阅Javadoc并不一定是学习这些库最有效的方式。在此,我们希望通过此文档为Guava中最流行和最强大的功能。提供更具可读性和解释性的说明。

译文格式说明

  • Guava中的类被首次引用时,都会链接到Guava的API文档。如:Optional<T>。
  • Guava和JDK中的方法被引用时。一般都会链接到Guava或JDK的API文档,一些人所共知的JDK方法除外。如:Optional.of(T), Map.get(key)。

  • 译者对文档的额外说明以斜体显示,而且以“译者注:”開始。

文件夹

1. 基本工具 [Basic utilities]

让使用Java语言变得更舒适

1.1 使用和避免null:null是模棱两可的,会引起令人困惑的错误。有些时候它让人非常不舒服。

非常多Guava工具类用高速失败拒绝null值,而不是盲目地接受

1.2 前置条件: 让方法中的条件检查更简单

1.3 常见Object方法: 简化Object方法实现。如hashCode()和toString()

1.4 排序: Guava强大的”流畅风格比較器”

1.5 Throwables:简化了异常和错误的传播与检查

2. 集合[Collections]

Guava对JDK集合的扩展,这是Guava最成熟和为人所知的部分

2.1 不可变集合: 用不变的集合进行防御性编程和性能提升。

2.2 新集合类型: multisets, multimaps, tables, bidirectional maps等

2.3 强大的集合工具类: 提供java.util.Collections中没有的集合工具

2.4 扩展工具类:让实现和扩展集合类变得更easy。比方创建Collection的装饰器,或实现迭代器

3. 缓存[Caches]

Guava Cache:本地缓存实现,支持多种缓存过期策略

4. 函数式风格[Functional idioms]

Guava的函数式支持能够显著简化代码。但请慎重使用它

5. 并发[Concurrency]

强大而简单的抽象,让编写正确的并发代码更简单

5.1 ListenableFuture:完毕后触发回调的Future

5.2 Service框架:抽象可开启和关闭的服务,帮助你维护服务的状态逻辑

6. 字符串处理[Strings]

非常实用的字符串工具。包括切割、连接、填充等操作

7. 原生类型[Primitives]

扩展 JDK 未提供的原生类型(如int、char)操作, 包括某些类型的无符号形式

8. 区间[Ranges]

可比較类型的区间API。包括连续和离散类型

9. I/O

简化I/O尤其是I/O流和文件的操作,针对Java5和6版本号

10. 散列[Hash]

提供比Object.hashCode()更复杂的散列实现。并提供布鲁姆过滤器的实现

11. 事件总线[EventBus]

公布-订阅模式的组件通信,但组件不须要显式地注冊到其它组件中

12. 数学运算[Math]

优化的、充分測试的数学工具类

13. 反射[Reflection]

Guava 的 Java 反射机制工具类

     中文參考站点:http://ifeve.com/google-guava/

二、Guava学习笔记:Preconditions优雅的检验參数

  在日常开发中。我们常常会对方法的输入參数做一些数据格式上的验证,以便保证方法能够依照正常流程运行下去。对于可预知的一些数据上的错误。我们一定要做事前检測和推断,来避免程序流程出错,而不是全然通过错误处理来保证流程正确运行,毕竟错误处理是比較消耗资源的方式。

在寻常情况下我们对參数的推断都须要自己来逐个写方法推断,代码量不少而且复用性不高,例如以下所看到的:

复制代码
import org.junit.Test;public class PreconditionsTest {@Testpublic 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("參数输入有误。");}}
}
复制代码

  说明:參数验证。我们每次都要加入if语句来做推断, 反复的工作会做好多次。getPerson方法仅仅有2个參数。验证规则也不是非常复杂,假设參数过度,验证规则复杂后,上面代码的可读性都会非常差的,复用性就更谈不上了。

  Guava类库中提供了一个作參数检查的工具类--Preconditions类, 该类能够大大地简化我们代码中对于參数的预推断和处理。让我们对方法输入參数的验证实现起来更加简单优雅。以下我们看看Preconditions类的使用实例:

Preconditions里面的方法:

  1 .checkArgument(boolean) :
  功能描写叙述:检查boolean是否为真。 用作方法中检查參数
  失败时抛出的异常类型: IllegalArgumentException

  2.checkNotNull(T):     
  功能描写叙述:检查value不为null, 直接返回value;
  失败时抛出的异常类型:NullPointerException

  3.checkState(boolean):
  功能描写叙述:检查对象的一些状态。不依赖方法參数。 比如, Iterator能够用来next是否在remove之前被调用。
  失败时抛出的异常类型:IllegalStateException

  4.checkElementIndex(int index, int size):
  功能描写叙述:检查index是否为在一个长度为size的list, string或array合法的范围。 index的范围区间是[0, size)(包括0不包括size)。

无需直接传入list, string或array, 仅仅需传入大小。返回index。  
  失败时抛出的异常类型:IndexOutOfBoundsException


  5.checkPositionIndex(int index, int size):
  功能描写叙述:检查位置index是否为在一个长度为size的list。 string或array合法的范围。 index的范围区间是[0, size)(包括0不包括size)。无需直接传入list。 string或array, 仅仅需传入大小。返回index。


  失败时抛出的异常类型:IndexOutOfBoundsException

  6.checkPositionIndexes(int start, int end, int size):
  功能描写叙述:检查[start, end)是一个长度为size的list。 string或array合法的范围子集。

伴随着错误信息。


  失败时抛出的异常类型:IndexOutOfBoundsException

  一个比較实用实例:

复制代码
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import com.google.common.base.Preconditions;public class PreconditionsTest {@Testpublic 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为null");Preconditions.checkArgument(neme.length()>0, "neme为\'\'");Preconditions.checkArgument(age>0, "age 必须大于0");System.out.println("a person age:"+age+",neme:"+neme);}public static void checkState(List<Integer> intList,int index)throws Exception{//表达式为true不抛异常Preconditions.checkState(intList.size()<index, " intList size 不能大于"+index);}public static void checkPositionIndex(List<Integer> intList,int index) throws Exception{Preconditions.checkPositionIndex(index, intList.size(), "index "+index+" 不在 list中。 List size为:"+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 为 "+index+" 不在 list中, List size为: "+intList.size());}
}
复制代码

  输出结果:

复制代码
a person age:8,neme:peida
age 必须大于0
neme为''
neme为nullintList size 不能大于9
index 13 不在 list中, List size为: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)
index 为 16 不在 list中, List size为: 9 (16) must be less than size (9)
复制代码

 

  Guava的preconditions有这样几个长处:

  在静态导入后, 方法非常明白无歧义, checkNotNull能够清楚地告诉你它是干什么的, 它会抛出如何的异常.
  checkNotNull在验证通过后直接返回, 能够这样方便地写代码: this.field = checkNotNull(field).
      简单而又强大的可变參数'printf'风格的自己定义错误信息.

參考文章:http://www.cnblogs.com/peida/archive/2013/06/17/Guava_Preconditions.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/390588.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

HTML DOM方法

querySelector() (querySelector()) The Document method querySelector() returns the first element within the document that matches the specified selector, or group of selectors. If no matches are found, null is returned.Document方法querySelector()返回文档中与…

leetcode 773. 滑动谜题

题目 在一个 2 x 3 的板上&#xff08;board&#xff09;有 5 块砖瓦&#xff0c;用数字 1~5 来表示, 以及一块空缺用 0 来表示. 一次移动定义为选择 0 与一个相邻的数字&#xff08;上下左右&#xff09;进行交换. 最终当板 board 的结果是 [[1,2,3],[4,5,0]] 谜板被解开。…

数据科学领域有哪些技术_领域知识在数据科学中到底有多重要?

数据科学领域有哪些技术Jeremie Harris: “In a way, it’s almost like a data scientist or a data analyst has to be like a private investigator more than just a technical person.”杰里米哈里斯(Jeremie Harris) &#xff1a;“ 从某种意义上说&#xff0c;这就像是数…

python 算术运算

1. 算术运算符与优先级 # -*- coding:utf-8 -*-# 运算符含有,-,*,/,**,//,% # ** 表示^ , 也就是次方 a 2 ** 4 print 2 ** 4 , aa 16 / 5 print 16 / 5 , aa 16.0 / 5 print 16.0 / 5 , a# 结果再进行一次floor a 16.0 // 5.0 print 16.0 // 5.0 , aa 16 // 5 print …

c语言编程时碰到取整去不了_碰到编程墙时如何解开

c语言编程时碰到取整去不了Getting stuck is part of being a programmer, no matter the level. The so-called “easy” problem is actually pretty hard. You’re not exactly sure how to move forward. What you thought would work doesn’t.无论身在何处&#xff0c;陷…

初创公司怎么做销售数据分析_为什么您的初创企业需要数据科学来解决这一危机...

初创公司怎么做销售数据分析The spread of coronavirus is delivering a massive blow to the global economy. The lockdown and work from home restrictions have forced thousands of startups to halt expansion plans, cancel services, and announce layoffs.冠状病毒的…

leetcode 909. 蛇梯棋

题目 N x N 的棋盘 board 上&#xff0c;按从 1 到 N*N 的数字给方格编号&#xff0c;编号 从左下角开始&#xff0c;每一行交替方向。 例如&#xff0c;一块 6 x 6 大小的棋盘&#xff0c;编号如下&#xff1a; r 行 c 列的棋盘&#xff0c;按前述方法编号&#xff0c;棋盘格…

Python基础之window常见操作

一、window的常见操作&#xff1a; cd c:\ #进入C盘d: #从C盘切换到D盘 cd python #进入目录cd .. #往上走一层目录dir #查看目录文件列表cd ../.. #往上上走一层目录 二、常见的文件后缀名&#xff1a; .txt 记事本文本文件.doc word文件.xls excel文件.ppt PPT文件.exe 可执行…

WPF效果(GIS三维篇)

二维的GIS已经被我玩烂了&#xff0c;紧接着就是三维了&#xff0c;哈哈&#xff01;先来看看最简单的效果&#xff1a; 转载于:https://www.cnblogs.com/OhMonkey/p/8954626.html

css注释_CSS注释示例–如何注释CSS

css注释Comments are used in CSS to explain a block of code or to make temporary changes during development. The commented code doesn’t execute.CSS中使用注释来解释代码块或在开发过程中进行临时更改。 注释的代码不执行。 Both single and multi-line comments in…

r软件时间序列分析论文_高度比较的时间序列分析-一篇论文评论

r软件时间序列分析论文数据科学 &#xff0c; 机器学习 (Data Science, Machine Learning) In machine learning with time series, using features extracted from series is more powerful than simply treating a time series in a tabular form, with each date/timestamp …

leetcode 168. Excel表列名称

题目 给你一个整数 columnNumber &#xff0c;返回它在 Excel 表中相对应的列名称。 例如&#xff1a; A -> 1 B -> 2 C -> 3 … Z -> 26 AA -> 27 AB -> 28 … 示例 1&#xff1a; 输入&#xff1a;columnNumber 1 输出&#xff1a;“A” 示例 2&…

飞机订票系统

1 #include <stdio.h>2 #include <stdlib.h>3 #include <string.h>4 #include <conio.h>5 typedef struct flightnode{6 char flight_num[10]; //航班号7 char start_time[10]; //起飞时间8 char end_time[10]; //抵达时间9 char st…

解决Mac10.13 Pod报错 -bash: /usr/local/bin/pod: /System/Library/Frameworks/Ruby.fram

升级10.13以后Pod命令失效&#xff0c;解决办法如下&#xff1a; 终端执行 brew link --overwrite cocoapods 复制代码尝试 Pod 命令是否已经恢复 若报错继续执行 brew reinstall cocoapodsbrew install rubybrew link --overwrite cocoapods 复制代码尝试 Pod 命令是否已经恢复…

angular示例_用示例解释Angular动画

angular示例为什么要使用动画&#xff1f; (Why use Animations?) Modern web components frequently use animations. Cascading Style-sheets (CSS) arms developers with the tools to create impressive animations. Property transitions, uniquely named animations, mu…

selenium抓取_使用Selenium的网络抓取电子商务网站

selenium抓取In this article we will go through a web scraping process of an E-Commerce website. I have designed this particular post to be beginner friendly. So, if you have no prior knowledge about web scraping or Selenium you can still follow along.在本文…

剑指 Offer 37. 序列化二叉树

题目 序列化是将一个数据结构或者对象转换为连续的比特位的操作&#xff0c;进而可以将转换后的数据存储在一个文件或者内存中&#xff0c;同时也可以通过网络传输到另一个计算机环境&#xff0c;采取相反方式重构得到原数据。 请设计一个算法来实现二叉树的序列化与反序列化…

ie8 ajaxSubmit 上传文件提示下载

转载 解决ie下ajaxsubmit上传文件提示下载文件问题 主要是应为放回类型为json&#xff0c;返回text/html转载于:https://www.cnblogs.com/yang-C-J/p/8963278.html

一个简单的 js 时间对象创建

JS中获取时间很常见&#xff0c;凑凑热闹&#xff0c;也获取一个时间对象试试 首先&#xff0c;先了解js的获取时间函数如下&#xff1a; var myDate new Date(); //创建一个时间对象 myDate.getYear(); // 获取当前年份&#xff08;2位&#x…

裁判打分_内在的裁判偏见

裁判打分News flash: being an umpire is hard. Their job is to judge whether a ball that’s capable of moving upwards of 100 MPH or breaking 25 inches crossed through an imaginary zone before being caught. I don’t think many would argue that they have it ea…