Java中判断Integer类型的值是否相等

例子

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

解释

  1. 当用“==”进行比较时,jvm默认是比较数据在java堆的地址;用equals()是比较对象的值
  2. 当数值在-128~127之间时,jvm会自动将Integer转成int数值进行比较,超过这个范围会按Integer对象来比较
  3. ==是一个关系运算符,如果比较的两端都为基本数据类型,则判断两者的值是否相等,(判断过程中还有不同基本类型的转化,这里不做讨论);如果比较的两端都为引用类型的话,则比较两者所指向对象的地址是否相同;对于equals方法,如果对象所在的类重写了equals方法,则按照重写的方法进行比较,如果没有,则比较两者所指向对象的地址是否相同

参考博客:https://blog.csdn.net/yangfengjueqi/article/details/81121140

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值