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

      

  • 相关阅读:
    Codeforces Round #709 (Div. 2, based on Technocup 2021 Final Round)
    Codeforces Round #708 (Div. 2)
    Educational Codeforces Round 106 (Rated for Div. 2)
    ccf csp 202012-1
    带配额的文件系统 (带模拟)
    阔力梯的树
    Codeforces Round #707 (Div. 2, based on Moscow Open Olympiad in Informatics)
    如何获取某个网站IP地址?
    C++开发者眼中的Java关键字abstract
    Java代码中如何获文件名和行号等源码信息?
  • 原文地址:https://www.cnblogs.com/IcanFixIt/p/4512049.html
Copyright © 2011-2022 走看看