google guava基本操做认识 二

 

避免空指针

"Null sucks." -Doug Lea测试

"I call it my billion-dollar mistake." - Sir C. A. R. Hoare, on his invention of the null referencethis

 

1 粗心使用了null致使了不少bug ,迅速失败而不是默认接受null,对开发者更明智spa

2.null存在歧义,如 map.get(key) 能够理解为map中对应的值为null,或者是对应的值不在map中,null能够表示成功,也能够表示失败,能够表明任何事,使用明确的词比null更清晰3d

 

Optional指针

建立optional对象code

 

查询方法对象

公用方法blog

MoreObjects.firstNonNull(T,T)排序

Strings.接口

emptyToNull(String)

isNullOrEmpty(String)

nullToEmpty(String)

---------------------------------------------------

Preconditions

 

有三种使用方式

1 .没有参数,抛出异常信息 无相关错误信息

2 .有一个object 参数,抛出异常带object.toString()信息

3.有其余额外的字符长参数,按指定模版输出异常信息

-----------------------------------------------------------

 

排序Ordering

 

ordering 是 guava中流畅的比较器类,可以建造复杂的比较器,将他们应用的对象的集合

static方法

lexicographically 字典排序

 

------------------------------------------------------------------------------------------------

 

 

Common Object Utilities

 

equals

当对象的属性为null时,使用 Object 的equals方法时,须要判断是否为空才能使用.

Objects.equal 使得无需检查空指针

hashCode

 

Guava使用 objects.hashcode(Object ...)使得不须要手动建立hash值

在jdk7中提供了相同的方法

 

toString .

 

好的方法在测试时写入难,修改方便,使用MoreObjects.toStringHelper()建立好用的toString方法

MoreObjects.toStringHelper(Foo.class).add("x", 1).toString();

 

compare/compareTo

 

实现接口和相应的方法,实现起来比较痛苦,咱们能够考虑更好的方法

 

Guava中提供了ComparisonChain,执行懒式比较,只有在发现nonzero结果时执行。

 

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().<T>nullsLast())

.result();

相关文章
相关标签/搜索