我们在实际开发中,经常需要覆写Object中的equals,hashcode,toString方法,其实编写这些代码并不是很难,但很枯燥和乏味。
下面推荐Google的Guava jar包来覆写上面的方法。
直接上代码。
import com.google.common.base.MoreObjects; import com.google.common.base.Objects; import com.google.common.collect.ComparisonChain; public class Book implements Comparable<Book> { private String author; private String title; private String publisher; private String isbn; private double price; public Book(String author, String title, String publisher, String isbn, double price) { this.author = author; this.title = title; this.publisher = publisher; this.isbn = isbn; this.price = price; } public String getAuthor() { return author; } public String getTitle() { return title; } public String getPublisher() { return publisher; } public String getIsbn() { return isbn; } public double getPrice() { return price; } @Override public String toString() { return MoreObjects.toStringHelper(this) .omitNullValues() .add("title", title) .add("author", author) .add("publisher", publisher) .add("price",price) .add("isbn", isbn).toString(); } @Override public int hashCode() { return Objects.hashCode(title, author, publisher, isbn, price); } @Override public boolean equals(Object obj) { return Objects.equal(this, obj); } @Override public int compareTo(Book o) { return ComparisonChain.start() .compare(this.title, o.getTitle()) .compare(this.author, o.getAuthor()) .compare(this.publisher, o.getPublisher()) .compare(this.isbn, o.getIsbn()) .compare(this.price, o.getPrice()) .result(); }
还可以使用apache 的common包里的类来实现。相关的代码稍后附上。
原文:http://www.cnblogs.com/IcanFixIt/p/4815250.html