您的位置:首页 > 其它

细节之Integer数值(==)比较问题 4000

2017-08-31 15:32 281 查看
1.问题场景

先看如下一段代码
if(activity.getTotalCounts()==activity.getParticipationCounts())  {
long time = activity.getUpdatedAt().getTime()+60*30*1000;
vo.setProbableOpenTime(new Date(time));
}
1
2
3
4
1
2
3
4

activity.getTotalCounts() 和activity.getParticipationCounts()的值都是Integer类型,在两者数值都一样的时候,测试发现vo.setProbableOpenTime(new
Date(time)); 这段代码竟然有时候能执行到,有时候却不行。比如 都等于100时,能够执行到这段代码,都等于200时却不行了,好奇怪的问题,都是一样的数值怎么就有时候成立,有时候不成立呢!于是有了下面这段测试代码

2.Integer数值比较单元测试
@Test
public void IntegerTest() {

Integer a = 100;
Integer b = 100;
Integer c = 300;
Integer d = 300;
System.out.println(a==b);
System.out.println(c==d);
System.out.println(c.equals(d));
}
1
2
3
4
5
6
7
8
9
10
11
1
2
3
4
5
6
7
8
9
10
11

输出结果为: 

true 

false 

true 

结果可知,Integer 用==比较数值确实有时候成立,有时候却不行。

3.问题的本质 

想知道为啥有这么奇怪的结果,还是要看看源代码的,如下:
* This method will always cache values in the range -128 to 127,
* inclusive, and may cache other values outside of this range.
public static Integer valueOf(int i) {
assert IntegerCache.high >= 127;
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
1
2
3
4
5
6
7
8
9
1
2
3
4
5
6
7
8
9

Integer a = 100实际上调用了valueOf(int i)方法。 

这里low是-128,high是127,从方法的注释中可以得知,在[-128,127]之间,Integer总是缓存了相应数值对象,这样每次取值时都是同一个对象,而不在此区间时,则不一定会缓存,那么取出两个同样数值大小的对象则不是同一个对象,每次都会new Integer(i);,所以其对象的地址不同,则用==比较是自然不会成立。Integer缓存的目的正如注释所言better space and time performance by caching frequently requested values.但是个人以为这样的设计又何尝不是雷区!

为了防止不小心掉入这样的陷阱,对于基本类型的比较,用“==”;而对于基本类型的封装类型和其他对象,应该调用public boolean equals(Object obj)方法(复杂对象需要自己实现equals方法)。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: