版权声明:本文为博主原创文章,转载请注明出处 https://blog.csdn.net/HughGilbert/article/details/71438306
Guava本质就是一些工具类,口号是优化了代码,但是目前为止,有些地方优化得不是很懂,现在的感觉就是总体来说就是逼格提高了
前置条件之Preconditions类
- Preconditions类中包含的方法:
方法名 | 作用 | 检查失败时抛出的异常 |
---|---|---|
checkArgument(boolean) |
检查boolean是否为true,用来检查传递给方法的参数 | IllegalArgumentException |
checkNotNull |
检查value是否为null,该方法直接返回value,因此可以内嵌使用checkNotNull | NullPointerException |
checkState(boolean) |
用来检查对象的某些状态 | IllegalStateException |
checkPositionIndex(int index, int size) |
检查index作为索引值对某个列表、字符串或数组是否有效,index属于[0,size) | IndexOutOfBoundsException |
checkPositionIndexs(int start, int end,int size) |
检查[start, end]表示的位置范围对某个列表、字符串或数组是否有效 | IndexOutOfBoundsException |
- Preconditions类中的每一个方法都有三个变种:
1. 没有额外的参数:判处的异常没有错误信息
2. 有一个Object对象作为参数,抛出的异常使用Object.toString()作为错误消息
3. 有一个String对象作为额外参数,并且有一组任意数量的附加Object对象:这个变种处理异常消息的方式有点类似printf,但考虑GWT的兼容性和效率,只支持%s指示符
- 举例说明:
Objects类 V.S. Object类
- guava通过Objects类来优化了Object类的equals()、hashCode()、toString()以及compare()和compareTo()
equals()
- 当一个对象中的字段可以为null时,实现Object.equals方法会很痛苦,因为不得不分别对它们进行null检查。使用Objects.equal帮助你执行null敏感的equals判断,从而避免抛出NullPointerException,(主要是可以不用自己实现equals()方法,并且添加了对null的判断)
Objects.equal("a", "a"); // returns true
Objects.equal(null, "a"); // returns false
Objects.equal("a", null); // returns false
Objects.equal(null, null); // returns true
...
import com.google.common.base.Objects;
...
public class Demo
{
...
public boolean equals(Object otherObject)
{
return Objects.equal(this,otherObject);
}
...
}
hashCode()
- 也是简化了传统对Object类中hashCode()方法的重写
...
import com.google.common.base.Objects;
...
public class Demo
{
String parameterOne;
String parameterTwo;
...
public int hashCode()
{
return Objects.hashCode(parameterOne,parameterTwo);
}
/*原始写法
public int hashCode()
{
return 7*parameterOne+11*parameterTwo();
}
*/
}
toString()
- 好的toString方法在调试时是无价之宝,但是编写toString方法有时候却很痛苦。使用 Objects.toStringHelper可以轻松编写有用的toString方法
// Returns "ClassName{x=1}"
Objects.toStringHelper(this).add("x", 1).toString();
// Returns "MyObject{x=1}"
Objects.toStringHelper("MyObject").add("x", 1).toString();
compare和compareTo
- 实现一个比较器Comparator,或者直接实现Comparable接口有时也伤不起。考虑一下这种情况(注意:并不是所有情况):
class Person implements Comparable<Person> {
private String lastName;
private String firstName;
private int zipCode;
public int compareTo(Person other) {
int cmp = lastName.compareTo(other.lastName);
if (cmp != 0) {
return cmp;
}
cmp = firstName.compareTo(other.firstName);
if (cmp != 0) {
return cmp;
}
return Integer.compare(zipCode, other.zipCode);
}
}
- ComparisionChain:ComparisonChain执行一种懒比较,它执行比较操作直至发现非零的结果,在那之后的比较输入将被忽略。
//guava 链式风格
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().nullsLast())
.result();
}