zoukankan      html  css  js  c++  java
  • Google Guava学习笔记——基础工具类针对Object类的使用

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

      

  • 相关阅读:
    1052 Linked List Sorting (25 分)
    1051 Pop Sequence (25 分)
    1050 String Subtraction (20 分)
    1049 Counting Ones (30 分)
    1048 Find Coins (25 分)
    1047 Student List for Course (25 分)
    1046 Shortest Distance (20 分)
    1045 Favorite Color Stripe (30 分)
    1044 Shopping in Mars (25 分)
    1055 The World's Richest (25 分)
  • 原文地址:https://www.cnblogs.com/IcanFixIt/p/4512049.html
Copyright © 2011-2022 走看看