Objects.equals方法JDK7,Java比较两个对象是否相等最简洁的方法

田信然
2023-12-01

以前我们判断对象是否相等,可能会这么写:

"test".equals(object);

在jdk7以后,java引入了比较两个对象的新的方法,Objects.equals(Object a, Object b) ,非常方便,直接调用即可,避免空指针异常。

import java.util.Objects;

/**
 * @author xasnow
 * @Date 2020/1/1
 */
public class ObjectEqualDemo {
    public static void main(String[] args) {
        ObjectEqualDemo objectEqualDemo = new ObjectEqualDemo();
        ObjectEqualDemo objectEqualDemo2 = new ObjectEqualDemo();
        boolean equals = Objects.equals(objectEqualDemo, objectEqualDemo2);
        System.out.println(equals); //false
        boolean equals2 = Objects.equals(objectEqualDemo, objectEqualDemo);
        System.out.println(equals2); //true
    }
}

源码如下:

    /**
     * Returns {@code true} if the arguments are equal to each other
     * and {@code false} otherwise.
     * 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.
     *
     * @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));
    }

 

 类似资料: