---
title: "Guava学习"
author: "chenchi1985"
date: "2012-11-02T19:18:30Z"
tags: []
categories: ["开源软件"]
slug: "guava"
draft: false
lastmod: "2012-11-02T19:18:30Z"
id: 1714677
url: "https://chenchi1985.iteye.com/blog/1714677"
---

# Preconditions

用于验证对象的各种状态，可以将这个类里面的方法静态导入，就和导入junit的各种assert一样。

```
import static com.google.common.base.Preconditions.*;
```

每个验证方法都可以多个参数，第一个变量代表了对象或一些逻辑判断，第二个参数为错误信息， 从第三个开始就是需要插入到错误信息里的变量了：

```
checkArgument(i >= 0, "Argument was %s but expected nonnegative", i);
checkArgument(i < j, "Expected i < j, but %s > %s", i, j);
```

 主要的验证方法如下:

```
checkArgument(boolean)
checkNotNull(T)
checkState(boolean)
checkElementIndex(int index, int size)
checkPositionIndex(int index, int size)
checkPositionIndexes(int start, int end, int size)
```

 

# Object common methods

## equals

如果一个对象可能为null，就不能直接调用这个对象的equal方法：

```
Objects
.
equal
(
"a"
,
 
"a"
);
 
// returns true


Objects
.
equal
(
null
,
 
"a"
);
 
// returns false


Objects
.
equal
(
"a"
,
 
null
);
 
// returns false


Objects
.
equal
(
null
,
 
null
);
 
// returns true
 
```

## hashCode

```
Objects.hashCode(field1, field2, ..., fieldn)
```

## 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

```
   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();
   }
```