Integer比较时用==还是equals

素颜马尾好姑娘i 2023-09-30 18:53 52阅读 0赞

目录

一、==

二、修改integer的缓存范围

三、使用equals


一、==

一般情况在代码代码中比较interger的值时用==是没有问题的,但是也存在一定的范围。

可以看到,当Integer表示的值在[-128 ~ 127]之间,使用==时能达到我们的预期的。

6c95d88d36604025ac168c58cc81e4cc.png

可是一旦超过这个范围,结果就不是我们想要的了。

bd67e432096b43ca945f335c9a4f41c8.png

如上图,我们看到一旦integer超过了[-128~127],==比较的结果为false;

这是因为Integer在进行比较的时候会自动的进行拆箱操作,而进行拆箱操作的时候会调用valueOf方法。

源码:

  1. public static Integer valueOf(int i) {
  2. if (i >= IntegerCache.low && i <= IntegerCache.high)
  3. return IntegerCache.cache[i + (-IntegerCache.low)];
  4. return new Integer(i);
  5. }

而IntegerCache.low ~ IntegerCache.high是从IntegerCache中获取的,IntegerCache缓存范围是[-128~127],一旦超出这个范围就得不到预期的结果。

源码如下:

  1. private static class IntegerCache {
  2. static final int low = -128;
  3. static final int high;
  4. static final Integer cache[];
  5. static {
  6. // high value may be configured by property
  7. int h = 127;
  8. String integerCacheHighPropValue =
  9. sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
  10. if (integerCacheHighPropValue != null) {
  11. try {
  12. int i = parseInt(integerCacheHighPropValue);
  13. i = Math.max(i, 127);
  14. // Maximum array size is Integer.MAX_VALUE
  15. h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
  16. } catch( NumberFormatException nfe) {
  17. // If the property cannot be parsed into an int, ignore it.
  18. }
  19. }
  20. high = h;
  21. cache = new Integer[(high - low) + 1];
  22. int j = low;
  23. for(int k = 0; k < cache.length; k++)
  24. cache[k] = new Integer(j++);
  25. // range [-128, 127] must be interned (JLS7 5.1.7)
  26. assert IntegerCache.high >= 127;
  27. }
  28. private IntegerCache() {}
  29. }

二、修改integer的缓存范围

当然这个缓存范围是可以修改的,如下图操作:

-XX:AutoBoxCacheMax=200

5b732e029ea74bb186fe9cc376e21ef8.png

测试:

修改自动拆箱的缓存最大值为200时,得到验证。

3d173ae526a640a88c2b33f659b9dca0.png

三、使用equals

3c48c380267840e1aa417558670b15ad.png

分析:

equals方法底层调用了intValue()方法。

  1. public boolean equals(Object obj) {
  2. if (obj instanceof Integer) {
  3. return value == ((Integer)obj).intValue();
  4. }
  5. return false;
  6. }

结论:在使用Integer比较数值相等时,建议使用equals。

发表评论

表情:
评论列表 (有 0 条评论,52人围观)

还没有评论,来说两句吧...

相关阅读