关于Java的Byte和Integer的equals及==对比方式的问题

Byte a = 1;
Byte b = new Byte("1");
Byte c = 0x1;
System.out.println(a.equals(1));
System.out.println(a==1);
System.out.println(a.equals(b));
System.out.println(a==b);
System.out.println(c.equals(1));
System.out.println(c==1);
System.out.println("======================");
Integer i = 1;
System.out.println(i.equals(1));
System.out.println(i==1);


图片说明

如上面的代码,为什么Byte的equals不能直接跟1比?比较结果为false;而Integer却可以?

/**
* Compares this object to the specified object. The result is
* {@code true} if and only if the argument is not
* {@code null} and is an {@code Integer} object that
* contains the same {@code int} 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 Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}

       * Returns an {@code Integer} instance representing the specified
 * {@code int} value.  If a new {@code Integer} instance is not
 * required, this method should generally be used in preference to
 * the constructor {@link #Integer(int)}, as this method is likely
 * to yield significantly better space and time performance by
 * caching frequently requested values.
 *
 * This method will always cache values in the range -128 to 127,
 * inclusive, and may cache other values outside of this range.
 *
 * @param  i an {@code int} value.
 * @return an {@code Integer} instance representing {@code i}.
 * @since  1.5
 */
public static Integer valueOf(int i) {
    if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
}

       /**
 * 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 Byte} object that
 * contains the same {@code byte} 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 Byte) {
        return value == ((Byte)obj).byteValue();
    }
    return false;
}

    Integer的equals方法是转为int类型 ,Byte的equals是byte类型  ,1是int类型

Byte.equals方法结果为true的前提是比较双方均为Byte类型。
a.equals(1)返回值为false的原因就是不满足这个要求。

1 这个常量默认是int类型,关于这点,官方文档有说明:
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

下面是这部分文字的截图:
图片说明

如果对您有帮助,请采纳答案好吗,谢谢!

这个问题我觉得就是说,equals()方法传入的参数是一个Object,是一个对下象,1这样的int基本类型涉及到对象层次的操作时会自动包装成Integer,
Integer和Byte两个不同的引用类型相比较肯定时返回false的,Integer可以比较的原因也在这里。

Object类中的equals方法和“==”是一样的,没有区别,而String类,Integer类等等一些类,是重写了equals方法,才使得equals和“==不同”
总之;
“==”比较的是值【变量(栈)内存中存放的对象的(堆)内存地址】
equal用于比较两个对象的值是否相同【不是比地址】但是似乎,每个被类重写的equals方法,在比较的时候,先看看是不是同一类型;
还要注意,Integer -128-127,是共享的。按Ctrl看看源码。。。。