zoukankan      html  css  js  c++  java
  • [Guava官方文档翻译] 5. Guava的Object公共方法 (Common Object Utilities Explained)

    我的技术博客经常被流氓网站恶意爬取转载。请移步原文:http://www.cnblogs.com/hamhog/p/3537367.html,享受整齐的排版、有效的链接、正确的代码缩进、更好的阅读体验。

    Object 公共方法

    equals

    当你的对象里有的域允许 null 值时,实现 Object.equals 方法会很麻烦,因为你必须单独检查 null 。使用 Objects.equal 方法可以完成考虑null(null-sensitive)的 equals 检查,而不用担心会出现 NullPointerException 。

    Objects.equal("a","a");// returns true
    Objects.equal(null,"a");// returns false
    Objects.equal("a",null);// returns false
    Objects.equal(null,null);// returns true

    注意: JDK 7中新引入的 Objects 类提供了等价的 Objects.equals 方法。

    hashCode

    综合一个 Object 所有的域得到hash值的过程可以更简单。Guava的 Objects.hashCode(Object...) 方法可以综合指定的域序列得出一个合理的、与域顺序相关的(order-sensitive)hash值。使用 Objects.hashCode(field1, field2, ..., fieldn) 来代替手工计算 hash 。

    注意: JDK 7中新引入的 Objects 类提供了等价的 Objects.hash(Object...) 方法。

    toString

    良好的 toString 方法对debug很有价值,但写起来很麻烦。使用 Objects.toStringHelper 来简便地编写可用的 toString 方法。以下是两个简单的例子:

        // Returns "ClassName{x=1}"
        Objects.toStringHelper(this)
            .add("x",1)
            .toString();
    
       // Returns "MyObject{x=1}"
       Objects.toStringHelper("MyObject")
           .add("x",1)
           .toString();

    compare/compareTo

    直接实现 Comparator 或 Comparable 接口可能很麻烦。例如:

    class Person implements Comparable<Person>{
        private String lastName;
        private String firstName;
        private int zipCode;
      
        public int compareTo(Person other){
            int cmp = lastName.compareTo(other.lastName);
            if(cmp != 0){
                return cmp;
            }
            cmp = firstName.compareTo(other.firstName);
            if(cmp != 0){
                return cmp;
            }
            return Integer.compare(zipCode, other.zipCode);
        }
    }

    这类代码容易杂乱,不易排除bug,而且冗长得让人烦。应该有更好的办法。

    为此,Guava提供了 ComparisonChain 。

    ComparisonChain 实施 "短路" 比较法:它在没有遇到非0(不等)结果之前,会一直比较下去;遇到了非0结果,就忽略后面的所有输入。

        public int compareTo(Foo that){
            return ComparisonChain.start()
                .compare(this.aString, that.aString)
                .compare(this.anInt, that.anInt)
                .compare(this.anEnum, that.anEnum, Ordering.natural().nullsLast())
                .result();
        }

    这种流畅的用法可读性强得多,不易受笔误影响,并且不会做无用功。其中的高级比较工具是Guava的“流畅版Comparator”中的Ordering类,参见这里

    中文翻译自Guava官方文档:GuavaExplained - CommonObjectUtilitiesExplained 译者:戴仓薯

  • 相关阅读:
    CGI(通用网关接口)
    PHP简介
    SEO搜索引擎优化/URL
    使用表单标签,与用户交互
    认识<img>标签,为网页插入图片
    使用mailto在网页中链接Email地址
    使用<a>标签,链接到另一个页面
    1037. Magic Coupon (25)
    1038. Recover the Smallest Number (30)
    1034. Head of a Gang (30) -string离散化 -map应用 -并查集
  • 原文地址:https://www.cnblogs.com/hamhog/p/3537367.html
Copyright © 2011-2022 走看看