zoukankan      html  css  js  c++  java
  • Google Guava--基础工具用法

    Optional

    Guava用Optional

    Optional常用方法:

        //创建指定引用的Optional实例,若引用为null则表示缺失
        Optional<Shop> optional1 = Optional.fromNullable(null); 
        //创建指定引用的Optional实例,若引用为null则抛出NullPointerException
        Optional<Shop> optional2 = Optional.of(new Shop(1,"name","addr","mobile",new Date()));
        
        //optional1.isPresent() 如果Optional包含非null的引用(引用存在),返回true
        System.out.println(optional1.isPresent());  //false
        System.out.println(optional2.isPresent());  //true
    
        //optional.or() //返回Optional所包含的引用,若引用缺失,返回指定的值
        Shop shop=optional1.or(new Shop());
        System.out.println(shop==null); //false
    
    

    借助ComparisonChain 实现 Comparable 接口

    如果我们不借助Guava,我们实现Comparable可能需要这样写:

        @Override
        public int compareTo(Shop that) {
            int result = shop_id.compareTo(that.getShop_id();
            if (result != 0) {
                return result;
            }
            result = shop_name.compareTo(that.getShop_name());
            return result;
        }
    

    当我们借助Guava ComparisonChain 实现 Comparable 接口我们可以这样写:

        @Override
        public int compareTo(Shop that) {
            return ComparisonChain.start()
                    .compare(this.shop_id,that.getShop_id())
                    .compare(this.shop_name,that.getShop_name())
                    .result();
        }
    
    

    MoreObjects.toStringHelper() 帮助重写toString()方法

        Shop newShop=new Shop(1,"帝都店","朝阳门","1111111",new Date());
        System.out.println(newShop);
        //demo.xxx.model.Shop@5babb90b
    

    当类没有重写toString()方法时会调用object的toString()方法,代码如下:

    public String toString() {
        return getClass().getName() + "@" + Integer.toHexString(hashCode());
    }
    

    有时候为了方便调试我们可以使用 MoreObjects.toStringHelper() 帮助我们重写toString方法。

        @Override
        public String toString() {
            return MoreObjects
                    .toStringHelper(this)
                    .add("shop_id", shop_id)
                    .add("shop_name",shop_name)
                    .add("create_time",create_time)
                    .toString();
        }
        //Shop{shop_id=1, shop_name=帝都店, create_time=Tue Jan 17 12:58:38 CST 2017}
    
  • 相关阅读:
    LeetCode#160-Intersection of Two Linked Lists-相交链表
    LeetCode#2-Add Two Numbers-两数相加
    LeetCode#141-Linked List Cycle-环形链表
    LeetCode#66-Plus One-加一
    LeetCode#35-Search Insert Position-搜索插入位置
    LeetCode#203-Remove Linked List Elements-移除链表元素
    基姆拉尔森公式
    [leetcode] 树(Ⅲ)
    常用算法合集(一)
    离散数学 II(最全面的知识点汇总)
  • 原文地址:https://www.cnblogs.com/javanoob/p/guava_basic_util.html
Copyright © 2011-2022 走看看