首页 > 其他 > 详细

使用第三方工具覆写Object中方法

时间:2015-09-17 09:58:26      阅读:176      评论:0      收藏:0      [点我收藏+]

我们在实际开发中,经常需要覆写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包里的类来实现。相关的代码稍后附上。

使用第三方工具覆写Object中方法

原文:http://www.cnblogs.com/IcanFixIt/p/4815250.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!