zoukankan      html  css  js  c++  java
  • guava学习--ComparisonChain

    转载:https://my.oschina.net/realfighter/blog/349824

    在日常的工作中,我们经常需要对两个对象进行比较,以找出其中的异同, Java中提供了compare/compareTo,我们需要实现一个比较器[Comparator],或者直接实现Comparable接口,不过当 对象的属性很多的时候,我们需要写大量的if else代码,代码不够优雅,Guava为我们简化了这一点,我们可以使用ComparisonChain类来优雅的实现对象之间的比较。

    可以用来排序,可作为默认的排序依据。

    年纪也不小了,到了相亲的年纪,家里找了两个媒婆:媒婆1和媒婆2,给了钱,媒婆挺办事,都介绍了一个好姑娘,居然还都叫lisa,那么就需要比较一下两个姑娘是不是同一个人了。

        

        我们唯一知道的就是两个姑娘的名字、身高和长相,我们也是通过这三点来进行比较,首先我们构造一个Girl对象,实现Comparable接口,来进行比较,传统方法,我们经常这样做:

    class Girl implements Comparable<Girl> {

    private String name;//名称
    private double height;//身高
    private String face;//长相

    Girl(String name, double height, String face) {
    this.name = name;
    this.height = height;
    this.face = face;
    }

    //传统方法我们这样比较
    @Override
    public int compareTo(Girl girl) {
    int c1 = name.compareTo(girl.name);
    if (c1 != 0){
    System.out.println("两个girl的name不相同");
    return c1;
    }
    int c2 = Double.compare(height, girl.height);
    if (c2 != 0){
    System.out.println("两个girl的height不相同");
    return c2;
    }
    int c3 = face.compareTo(girl.face);
    if(c3 !=0)
    System.out.println("两个girl的face不相同");
    return c3;
    }
    }

            然后,我们测试一下,居然不是一个人,该选择哪一个好呢?

    @Test
    public void testCompareTo() {
    Girl g1 = new Girl("lisa", 175.00, "nice");
    Girl g2 = new Girl("lisa", 175.00, "beauty");
    //两个girl的face不相同
    System.out.println(g1.compareTo(g2) == 0);//false
    }

        而使用Guava提供的ComparisonChain类,我们可以这样进行比较,如下:

    //使用Guava提供的ComparisonChain我们这样比较
    @Override
    public int compareTo(Girl girl) {
      return ComparisonChain.start()
        .compare(name, girl.name)
        .compare(height, girl.height)
        .compare(face, girl.face)
        .result();
    }

        翻开ComparisonChain类的源码,我们发现,它其实是一个抽象类,其提供了主要有三个抽象方法,start()用于返回内部的一个 ComparisonChain实现;重载了许多compare()方法,用于接收各种类型的参数,compare方法返回的仍然是 ComparisonChain对象;result()方法用于返回比较后的结果。

        总结:通过对ComparisonChain的学习,以及前面Guava中Obejects实用工具类的学习等,我们发现,Guava中大量存在这种类似的链式编码,熟悉设计模式的不难理解,这正是Builder建造者模式的应用。

  • 相关阅读:
    数据表的水平拆分
    高性能网站架构
    文本框内容改变触发事件
    树莓派3B(1)- Raspberry Pi 3B 安装系统并联网
    一年经验Java程序员面经小记
    Windows系统安装总结
    树莓派3B(2)- 配置多个wifi,自动寻找可用网络
    Centos7 Apache实现Http访问SVN资源库
    Centos7搭建svn服务
    读《重构 改善既有代码的设计》有感
  • 原文地址:https://www.cnblogs.com/fanguangdexiaoyuer/p/6252993.html
Copyright © 2011-2022 走看看