优秀的编程知识分享平台

网站首页 > 技术文章 正文

java Integer值比较(java integer 比较)

nanyue 2024-08-11 20:34:14 技术文章 9 ℃

所有相同类型的包装类对象之间的值比较,应该使用equals方法比较。

–来自阿里巴巴java开发手册。

先看个简单实例:

public static void main(String[] args)throws Exception{

Integer a = -121;

Integer b = -121;

Integer c = 345;

Integer d = 345;

System.out.println(a.equals(b));

System.out.println(a == b);

System.out.println(c.equals(d));

System.out.println(c == d);

}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

这段代码打印结果为:

true

true

true

false

  • 1
  • 2
  • 3
  • 4
  • 5

c和d的值都是345,为什么用==和equals比较结果不一样呢?

我们看下对象信息,注意对象地址:

Integer值的比较有个坑:对于Integer var = ?,在-128至127范围内的赋值, Integer 对象是在IntegerCache.cache 产生,会复用已有对象,这个区间内的 Integer 值可以直接使用==进行判断,但是这个区间之外的所有数据,都会在堆上产生,并不会复用已有对象;所以,在上面,我们的c和d两个,虽然值是一样的,但是地址不一样。

这是一个大坑,很多人会在项目中使用==来比较Integer!强烈建议,必须使用equals来比较!

最近发表
标签列表