您的位置:首页 > 移动开发 > Objective-C

Google Guava学习笔记——基础工具类针对Object类的使用

2015-05-19 14:23 477 查看
  Guava 提供了一系列针对Object操作的方法。

  1. toString方法

  为了方便调试重写toString()方法是很有必要的,但写起来比较无聊,不管如何,Objects类提供了toStringHelper方法,它用起来非常简单,我们可以看下面的代码:

  

public class Book implements Comparable<Book> {

private Person author;
private String title;
private String publisher;
private String isbn;
private double price;

/*
*  getter and setter methods
*/
public String toString() {
return Objects.toStringHelper(this)
.omitNullValues()
.add("title", title)
.add("author", author)
.add("publisher", publisher)
.add("price",price)
.add("isbn", isbn).toString();
}

}


  注意,在新的版本中,使用MoreObjects类的toStringHelper替代原来的方法,原来的方法deprecated了。

  2,检查是否为空值

    firstNonNull方法有两个参数,如果第一个参数不为空,则返回;如果为空,返回第二个参数。

    String value = Objects.firstNonNull("hello", "default value");

    注意,此方法也已经废弃了,可以使用 String value = MoreObjects.firstNonNull("hello", "default value"); 来代替。

  3,生成 hash code

public int hashCode() {
return Objects.hashCode(title, author, publisher, isbn,price);
}


  4,实现CompareTo方法

   我们以前的写法是这样的: 

public int compareTo(Book o) {
int result = this.title.compareTo(o.getTitle());
if (result != 0) {
return result;
}

result = this.author.compareTo(o.getAuthor());
if (result != 0) {
return result;
}

result = this.publisher.compareTo(o.getPublisher());
if(result !=0 ) {
return result;
}

return this.isbn.compareTo(o.getIsbn());
}


  改进后的方法:

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


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: