Objects

原文链接

1、常用API

equal / deepEqual

  • equal:基本类型,比较数值;引用类型,比较地址;
  • deepEqual:基本类型,比较数值;引用类型,比较地址,但是数组不会比较地址,会比较数组中的元素是否相等
        int[] a = new int[]{1,2,3};
        int[] b = new int[]{1,2,3};

        System.out.println(Objects.equals(a, b));// false
        System.out.println(Objects.deepEquals(a, b));// true
        System.out.println(a.equals(b));// false

        Person person1 = new Person();
        Person person2 = new Person();
        System.out.println(Objects.equals(person1, person2));// false
        System.out.println(Objects.deepEquals(person1, person2));// false
        System.out.println(person1.equals(person2));// false

hash / hasCode

  • int hashCode(Object o):计算单个对象的hashCode
  • int hash(Object… values):计算可变数组的hashCode
  	// 计算可变数组的hashCode
		public static int hash(Object... values) {
        return Arrays.hashCode(values);
    }

  	// 计算单个对象的hashCode
    public static int hashCode(Object o) {
        return o != null ? o.hashCode() : 0;
    }
  • Arrays.hasCode
    public static int hashCode(Object a[]) {
        if (a == null)
            return 0;

        int result = 1;

        for (Object element : a)
            result = 31 * result + (element == null ? 0 : element.hashCode());

        return result;
    }

toString()

    public static String toString(Object o) {
        return String.valueOf(o);
    }

    public static String toString(Object o, String nullDefault) {
        return (o != null) ? o.toString() : nullDefault;
    }

compare

  • 比较两个对象的大小,自定义Comparator
        Person person1 = new Person();
        person1.setAge(12);
        Person person2 = new Person();
        person2.setAge(16);
        int compare = Objects.compare(person1, person2, new Comparator<Person>() {
            @Override
            public int compare(Person o1, Person o2) {
                return o1.getAge() - o2.getAge();
            }
        });
        System.out.println(compare);// -4

requireNonNull / isNull / nonNull / requireNonNull

  • 一些判空的方法
  • T requireNonNull(T obj, Supplier messageSupplier):延迟提供消息
  • T requireNonNull(T obj, String message):直接创建消息
        Objects.requireNonNull(person1, new Supplier<String>() {
            @Override
            public String get() {
                return "empty展示的消息";
            }
        });

2、源码翻译

package java.util;

import java.util.function.Supplier;

/**
 * This class consists of {@code static} utility methods for operating
 * on objects.  These utilities include {@code null}-safe or {@code
 * null}-tolerant methods for computing the hash code of an object,
 * returning a string for an object, and comparing two objects.
 * 该类由static实用方法组成,用于操作对象。
 * 这些实用方法包括用于计算对象的哈希码的null-safe或null方法、返回对象的字符串、比较两个对象。
 *
 * @since 1.7
 */
public final class Objects {

    private Objects() {
        // 工具方法,不能被实例化
        throw new AssertionError("No java.util.Objects instances for you!");
    }

    /**
     * Returns {@code true} if the arguments are equal to each other
     * and {@code false} otherwise.
     * 如果参数相等返回true,否则false。
     * Consequently, if both arguments are {@code null}, {@code true}
     * is returned and if exactly one argument is {@code null}, {@code
     * false} is returned.  Otherwise, equality is determined by using
     * the {@link Object#equals equals} method of the first
     * argument.
     * 因此,如果两个参数都是null , 返回true。
     * 如果只有一个参数是null ,则返回false。否则,使用第一个参数的equals方法确定相等性。
     *
     * @param a an object
     * @param b an object to be compared with {@code a} for equality
     * @return {@code true} if the arguments are equal to each other
     * and {@code false} otherwise
     * @see Object#equals(Object)
     */
    public static boolean equals(Object a, Object b) {
        return (a == b) || (a != null && a.equals(b));
    }

   /**
    * Returns {@code true} if the arguments are deeply equal to each other
    * and {@code false} otherwise.
    * 返回true如果参数是深层相等,否则false。
    *
    * Two {@code null} values are deeply equal.  If both arguments are
    * arrays, the algorithm in {@link Arrays#deepEquals(Object[],
    * Object[]) Arrays.deepEquals} is used to determine equality.
    * Otherwise, equality is determined by using the {@link
    * Object#equals equals} method of the first argument.
    * 两个null值相当。
    * 如果两个参数都是数组,则使用Arrays.deepEquals中的算法来确定相等。
    * 否则,通过使用第一个参数的equals方法确定相等性。
    *
    * @param a an object
    * @param b an object to be compared with {@code a} for deep equality
    * @return {@code true} if the arguments are deeply equal to each other
    * and {@code false} otherwise
    * @see Arrays#deepEquals(Object[], Object[])
    * @see Objects#equals(Object, Object)
    */
    public static boolean deepEquals(Object a, Object b) {
        if (a == b)
            return true;
        else if (a == null || b == null)
            return false;
        else
            return Arrays.deepEquals0(a, b);
    }

    /**
     * Returns the hash code of a non-{@code null} argument and 0 for
     * a {@code null} argument.
     * 返回非空参数的hashcode,null则返回0
     *
     * @param o an object
     * @return the hash code of a non-{@code null} argument and 0 for
     * a {@code null} argument
     * @see Object#hashCode
     */
    public static int hashCode(Object o) {
        return o != null ? o.hashCode() : 0;
    }

   /**
    * Generates a hash code for a sequence of input values. The hash
    * code is generated as if all the input values were placed into an
    * array, and that array were hashed by calling {@link
    * Arrays#hashCode(Object[])}.
    * 为可变数组生成哈希码。 生成哈希码,就好像将所有输入值都放入数组一样,并且该数组通过调用Arrays.hashCode(Object[])进行哈希处理。
    *
    * <p>This method is useful for implementing {@link
    * Object#hashCode()} on objects containing multiple fields. For
    * example, if an object that has three fields, {@code x}, {@code
    * y}, and {@code z}, one could write:
    * 此方法是用于实现有用Object.hashCode()在含有多个字段的对象。 例如,如果有三个字段,对象x , y和z ,一个可以这样写:
    *
    * <blockquote><pre>
    * &#064;Override public int hashCode() {
    *     return Objects.hash(x, y, z);
    * }
    * </pre></blockquote>
    *
    * <b>Warning: When a single object reference is supplied, the returned
    * value does not equal the hash code of that object reference.</b> This
    * value can be computed by calling {@link #hashCode(Object)}.
    * 警告:当提供单个对象引用时,返回的值不等于该对象引用的哈希码。 该值可以通过调用hashCode(Object)来计算。
    *
    * @param values the values to be hashed
    * @return a hash value of the sequence of input values
    * @see Arrays#hashCode(Object[])
    * @see List#hashCode
    */
    public static int hash(Object... values) {
        return Arrays.hashCode(values);
    }

    /**
     * Returns the result of calling {@code toString} for a non-{@code
     * null} argument and {@code "null"} for a {@code null} argument.
     * 返回一个非空参数调用 toString和一个 空参数的 "null"的 null 。
     *
     * @param o an object
     * @return the result of calling {@code toString} for a non-{@code
     * null} argument and {@code "null"} for a {@code null} argument
     * @see Object#toString
     * @see String#valueOf(Object)
     */
    public static String toString(Object o) {
        return String.valueOf(o);
    }

    /**
     * Returns the result of calling {@code toString} on the first
     * argument if the first argument is not {@code null} and returns
     * the second argument otherwise.
     * 如果第一个参数不是 null ,则返回第一个参数调用 toString的结果, 否则toString返回第二个参数。
     *
     * @param o an object
     * @param nullDefault string to return if the first argument is
     *        {@code null}
     * @return the result of calling {@code toString} on the first
     * argument if it is not {@code null} and the second argument
     * otherwise.
     * @see Objects#toString(Object)
     */
    public static String toString(Object o, String nullDefault) {
        return (o != null) ? o.toString() : nullDefault;
    }

    /**
     * Returns 0 if the arguments are identical and {@code
     * c.compare(a, b)} otherwise.
     * Consequently, if both arguments are {@code null} 0
     * is returned.
     * 返回0,如果参数都是相同的, c.compare(a, b)其他。 因此,如果两个参数都为null则返回0。
     *
     * <p>Note that if one of the arguments is {@code null}, a {@code
     * NullPointerException} may or may not be thrown depending on
     * what ordering policy, if any, the {@link Comparator Comparator}
     * chooses to have for {@code null} values.
     * 请注意,如果其中一个参数为null ,则NullPointerException可能会或可能不会抛出,具体取决于Comparator选择具有null值的订购策略(如果有)。
     *
     * @param <T> the type of the objects being compared
     * @param a an object
     * @param b an object to be compared with {@code a}
     * @param c the {@code Comparator} to compare the first two arguments
     * @return 0 if the arguments are identical and {@code
     * c.compare(a, b)} otherwise.
     * @see Comparable
     * @see Comparator
     */
    public static <T> int compare(T a, T b, Comparator<? super T> c) {
        return (a == b) ? 0 :  c.compare(a, b);
    }

    /**
     * Checks that the specified object reference is not {@code null}. This
     * method is designed primarily for doing parameter validation in methods
     * and constructors, as demonstrated below:
     * 检查指定的对象引用不是null 。 该方法主要用于在方法和构造函数中进行参数验证,如下所示:
     *
     * <blockquote><pre>
     * public Foo(Bar bar) {
     *     this.bar = Objects.requireNonNull(bar);
     * }
     * </pre></blockquote>
     *
     * @param obj the object reference to check for nullity
     * @param <T> the type of the reference
     * @return {@code obj} if not {@code null}
     * @throws NullPointerException if {@code obj} is {@code null}
     */
    public static <T> T requireNonNull(T obj) {
        if (obj == null)
            throw new NullPointerException();
        return obj;
    }

    /**
     * Checks that the specified object reference is not {@code null} and
     * throws a customized {@link NullPointerException} if it is. This method
     * is designed primarily for doing parameter validation in methods and
     * constructors with multiple parameters, as demonstrated below:
     * 检查指定的对象引用不是null并抛出一个自定义的NullPointerException(如果是)。 该方法主要用于在具有多个参数的方法和构造函数中进行参数验证,如下所示:
     * <blockquote><pre>
     * public Foo(Bar bar, Baz baz) {
     *     this.bar = Objects.requireNonNull(bar, "bar must not be null");
     *     this.baz = Objects.requireNonNull(baz, "baz must not be null");
     * }
     * </pre></blockquote>
     *
     * @param obj     the object reference to check for nullity
     * @param message detail message to be used in the event that a {@code
     *                NullPointerException} is thrown
     * @param <T> the type of the reference
     * @return {@code obj} if not {@code null}
     * @throws NullPointerException if {@code obj} is {@code null}
     */
    public static <T> T requireNonNull(T obj, String message) {
        if (obj == null)
            throw new NullPointerException(message);
        return obj;
    }

    /**
     * Returns {@code true} if the provided reference is {@code null} otherwise
     * returns {@code false}.
     * 返回 true如果提供的引用是 null否则返回 false 。
     *
     * @apiNote This method exists to be used as a
     * {@link java.util.function.Predicate}, {@code filter(Objects::isNull)}
     * 这种方法存在着用作Predicate , filter(Objects::isNull)
     *
     * @param obj a reference to be checked against {@code null}
     * @return {@code true} if the provided reference is {@code null} otherwise
     * {@code false}
     *
     * @see java.util.function.Predicate
     * @since 1.8
     */
    public static boolean isNull(Object obj) {
        return obj == null;
    }

    /**
     * Returns {@code true} if the provided reference is non-{@code null}
     * otherwise returns {@code false}.
     * 返回 true如果提供的参考是非 null否则返回 false 。
     *
     * @apiNote This method exists to be used as a
     * {@link java.util.function.Predicate}, {@code filter(Objects::nonNull)}
     *
     * @param obj a reference to be checked against {@code null}
     * @return {@code true} if the provided reference is non-{@code null}
     * otherwise {@code false}
     *
     * @see java.util.function.Predicate
     * @since 1.8
     */
    public static boolean nonNull(Object obj) {
        return obj != null;
    }

    /**
     * Checks that the specified object reference is not {@code null} and
     * throws a customized {@link NullPointerException} if it is.
     *检查指定的对象引用不是null并抛出自定义的NullPointerException(如果是)。
     *
     * <p>Unlike the method {@link #requireNonNull(Object, String)},
     * this method allows creation of the message to be deferred until
     * after the null check is made. While this may confer a
     * performance advantage in the non-null case, when deciding to
     * call this method care should be taken that the costs of
     * creating the message supplier are less than the cost of just
     * creating the string message directly.
     *
     *
     * 与方法requireNonNull(Object, String)不同,该方法允许创建要延迟的消息,直到进行空检查为止。
     * 虽然这可能会在非空情况下赋予性能优势,但在决定调用此方法时,应注意创建消息提供者的成本低于直接创建字符串消息的成本。
     *
     * @param obj     the object reference to check for nullity
     * @param messageSupplier supplier of the detail message to be
     * used in the event that a {@code NullPointerException} is thrown
     *                        在发送 NullPointerException的情况下使用的详细消息的供应商
     * @param <T> the type of the reference
     * @return {@code obj} if not {@code null}
     * @throws NullPointerException if {@code obj} is {@code null}
     * @since 1.8
     */
    public static <T> T requireNonNull(T obj, Supplier<String> messageSupplier) {
        if (obj == null)
            throw new NullPointerException(messageSupplier.get());
        return obj;
    }
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值