细节之Integer数值(==)比较问题 4000
2017-08-31 15:32
281 查看
1.问题场景
先看如下一段代码
2
3
4
1
2
3
4
activity.getTotalCounts() 和activity.getParticipationCounts()的值都是Integer类型,在两者数值都一样的时候,测试发现vo.setProbableOpenTime(new
Date(time)); 这段代码竟然有时候能执行到,有时候却不行。比如 都等于100时,能够执行到这段代码,都等于200时却不行了,好奇怪的问题,都是一样的数值怎么就有时候成立,有时候不成立呢!于是有了下面这段测试代码
2.Integer数值比较单元测试
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.问题的本质
想知道为啥有这么奇怪的结果,还是要看看源代码的,如下:
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方法)。
先看如下一段代码
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方法)。
相关文章推荐
- Integer数值比较问题
- 关于Integer数值比较的问题以及不可变对象
- Integer对象用== 和equals比较大小的问题
- Java之Integer数值比较
- Integer陷阱(0~127和其他 数值相等对象比较)
- Integer与int比较的问题
- 关于Integer大小比较的问题
- iOS在不同手机转换时间戳获取到的数值进行比较会出现不同的值的问题
- java Integer 比较的问题
- Long的equals和相同数值的Integer比较为何为false?
- Java中int和Integer比较问题
- java Integer和int之间==的比较问题。求解释
- 两个值相同的Integer类型用!=比较出错的问题
- 有关Integer的比较问题
- Java 中 Integer 包装器类比较相等问题(拆箱、装箱、享元)
- 踩坑笔记之Integer数值比较
- Integer和int之间==的比较问题
- JAVA中Integer类型变量比较问题
- 【转】关于Integer大小比较的问题
- JavaScript字符串数值比较问题