关于Objects.equals()的一次比较,竟然出乎意料的返回了false

    public static void main(String[] args) {
        Long i = 1L;
        Integer i2 = 1;
        System.out.println(Objects.equals(i, i2));
    }

比较如上:

翻阅源码发现,下图也没什么不妥啊?

    /**
     * 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));
    }

 

在翻一次源码:!!!!!!!!!! if (obj instanceof Long) 

    /**
     * Compares this object to the specified object.  The result is
     * {@code true} if and only if the argument is not
     * {@code null} and is a {@code Long} object that
     * contains the same {@code long} value as this object.
     *
     * @param   obj   the object to compare with.
     * @return  {@code true} if the objects are the same;
     *          {@code false} otherwise.
     */
    public boolean equals(Object obj) {
        if (obj instanceof Long) {
            return value == ((Long)obj).longValue();
        }
        return false;
    }

这个地方注意:equals在不同类型之间是不等的。

posted @ 2020-02-10 21:19  CHANGEMAX  阅读(589)  评论(0编辑  收藏  举报