說道equal方法,相信大家都是有愛有恨,愛的是此方法可以很方便的進行兩個對象的是否相同比較,可恨的是你不知到調用他的對對象是否符合要求,也就是是不是會出現空指針調用也就是說如果這樣的調用:
new Object().equals(new Object());
本身這句代碼沒有錯,但是呢要是:以下的name是一個null的值怎麼辦,會出現怎麼樣的結果??
name.equals(name1);
這就是我們無法想象的錯誤,據瞭解世界上95%的程序bug於null有關,關於null 我們在以後的文章中在做具體的探討。
然而就是以上我們很容易出現問題的代碼,Guava在做了很好的包裝,以後就是使用他了,這樣我們可以很好的避免一些bug,而且還能很好的寫出好更加優雅的代碼。當然好的代碼還是要自我約束。培養代碼潔癖。
在來說一下Guava中的toString()方法和hashCode(),其實我寫這個不是說我們必須這樣寫,也就是看到這個模塊,我瞭解了一下java中的hashCode()方法的用意,下面我們來看一下java中的hashCode()的作用:提高數據在散列中的存儲效率。
java代碼中我們經常會重寫equals()方法,但是千萬要記住在重寫了equals()方法之後也要記得重寫hashCode()方法,爲什麼呢,這個我們在另外一篇文章中進行探討。
下面我們來看一下我們今天進行的Guava的學習筆記,廢話不說,上代碼:
compareTo(Person that) {
return ComparisonChain.start()
import com.google.common.base.Objects;
import com.google.common.collect.ComparisonChain;
import com.google.common.collect.Lists;
import com.google.common.collect.Ordering;
import java.util.Collections;
import java.util.List;
/**
* Created by luyangli on 15-9-16.
* <p/>
* 常見的Object方法
*/
public class ObjectTest {
public static void main(String[] args) {
System.out.println(Objects.equal("q", "q"));
System.out.println(Objects.equal("a", null));
System.out.println(Objects.equal(null, "a"));
System.out.println(Objects.equal(null, null));
System.out.println(Objects.hashCode("a", "b", "c"));
System.out.println(Objects.toStringHelper("ObjectTest").add("x", 1).toString());
//new Object().hashCode();
Person changhaha = new Person("常哈哈", 23);
Person lilulu = new Person("李露露", 24);
List<Person> personList = Lists.newArrayList();
personList.add(lilulu);
personList.add(changhaha);
for (Person person : personList) {
System.out.println(person.getName() + ":" + person.getAge());
}
System.out.println("====排序後====");
Collections.sort(personList);
for (Person person : personList) {
System.out.println(person.getName() + ":" + person.getAge());
}
}
static class Person implements Comparable<Person> {
private String name;
private int age;
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
// public int compareTo(Person other) {
// int i = this.name.compareTo(other.getName());
// if (0 == i) {
// return this.age - other.getAge();
// }
// return i;
// }
public int compareTo(Person that) {
return ComparisonChain.start()
.compare(this.getName(), that.getName())
.compare(this.getAge(), that.getAge())
.result();
}
}}
其中我屏蔽掉的是我使用常規的數據排序操作,我們來看一下我們的執行結果:
true false false true 126145 ObjectTest{x=1} 李露露:24 常哈哈:23 ====排序後==== 常哈哈:23 李露露:24
我們可以看到其實Guava就是對於我們可能犯得低級錯誤進行了預防,可是就是這樣的預防,我們很受用。