Google Guava学习笔记——基础工具类针对Object类的使用
2015-05-19 14:23
477 查看
Guava 提供了一系列针对Object操作的方法。
1. toString方法
为了方便调试重写toString()方法是很有必要的,但写起来比较无聊,不管如何,Objects类提供了toStringHelper方法,它用起来非常简单,我们可以看下面的代码:
注意,在新的版本中,使用MoreObjects类的toStringHelper替代原来的方法,原来的方法deprecated了。
2,检查是否为空值
firstNonNull方法有两个参数,如果第一个参数不为空,则返回;如果为空,返回第二个参数。
String value = Objects.firstNonNull("hello", "default value");
注意,此方法也已经废弃了,可以使用 String value = MoreObjects.firstNonNull("hello", "default value"); 来代替。
3,生成 hash code
4,实现CompareTo方法
我们以前的写法是这样的:
改进后的方法:
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(); }
相关文章推荐
- Google Guava学习笔记——基础工具类Joiner的使用
- Google Guava学习笔记——基础工具类Splitter的使用
- Java基础学习笔记13——(StringBuffer的使用,数组高级,Arrays工具类,Integer和Character等包装类)
- Guava学习笔记(二):Google Guava (瓜娃)的API快速熟悉使用
- Guava学习笔记:Google Guava 类库简介
- mybatis学习笔记(六)使用generator生成mybatis基础配置代码和目录结构
- Java基础学习笔记12——(Scanner的使用,String类的概述和使用样例)
- [学习笔记]MySQL基础使用
- Guava学习笔记(一):Google Guava 类库简介
- Guava学习笔记:Optional优雅的使用null
- Guava学习笔记:Google Guava 类库简介
- mybatis学习笔记(六)使用generator生成mybatis基础配置代码和目录结构
- Guava学习笔记:Google Guava 类库简介
- 【Google Guava 学习笔记 二】关于Optional,避免null对你的摧残
- 瓜娃子?【Google Guava 学习笔记 一】
- Guava库学习:学习使用Preconditions工具类进行代码的校验
- NodeJS基础学习笔记(三):使用NPM
- jq学习使用基础笔记
- NodeJS学习系列课程笔记(NodeJS util工具类相关使用方法)
- [原创]java WEB学习笔记49:文件上传基础,基于表单的文件上传,使用fileuoload 组件