例子
public class Demo {
public static void main(String[] args) {
Integer c = -128;
Integer d = -128;
System.out.println("c == d: " + (c == d));
System.out.println("c.equals(d): " + c.equals(d));
System.out.println("c.intValue() == d.intValue(): " + (c.intValue() == d.intValue()));
System.out.println("Objects.equals(c, d): " + Objects.equals(c, d));
Integer e = 127;
Integer f = 127;
System.out.println("e == f: " + (e == f));
System.out.println("e.equals(f): " + e.equals(f));
System.out.println("e.intValue() == f.intValue(): " + (e.intValue() == f.intValue()));
System.out.println("Objects.equals(e, f): " + Objects.equals(e, f));
Integer g = 128;
Integer h = 128;
System.out.println("g == h: " + (g == h));
System.out.println("g.equals(h): " + g.equals(h));
System.out.println("g.intValue() == h.intValue():" + (g.intValue() == h.intValue()));
System.out.println("Objects.equals(g, h): " + Objects.equals(g, h));
}
}
运行结果:
c == d: true
c.equals(d): true
c.intValue() == d.intValue(): true
Objects.equals(c, d): true
e == f: true
e.equals(f): true
e.intValue() == f.intValue(): true
Objects.equals(e, f): true
g == h: false
g.equals(h): true
g.intValue() == h.intValue():true
Objects.equals(g, h): true
解释
- 当用“==”进行比较时,jvm默认是比较数据在java堆的地址;用equals()是比较对象的值
- 当数值在-128~127之间时,jvm会自动将Integer转成int数值进行比较,超过这个范围会按Integer对象来比较
- ==是一个关系运算符,如果比较的两端都为基本数据类型,则判断两者的值是否相等,(判断过程中还有不同基本类型的转化,这里不做讨论);如果比较的两端都为引用类型的话,则比较两者所指向对象的地址是否相同;对于equals方法,如果对象所在的类重写了equals方法,则按照重写的方法进行比较,如果没有,则比较两者所指向对象的地址是否相同
参考博客:https://blog.csdn.net/yangfengjueqi/article/details/81121140