• Integer超出-128——127范围的数值比较为什么要用equals


    问题描述:
    之前在项目中遇到过一个问题,比较两个id是否相等,用的是进行判断,数据量不大的时候是没有问题的,随着数据量的增加,id值超过127问题就来了,两个相同的超过127的id值用比较返回false,通过百度搜索发现要用equals比较。
    通常到了这一步可能就不会再往下深究了,可是到面试的时候就彻底凉凉了,所以凡事还是多问个为什么。

    1,先来看==和equals的区别

    ==对于基本数据类型比较的是值,而对于引用类型比较的就是引用的地址,即两个引用是否指向同一个对象实例
     

    1. int a = 128;
    2. int b = 128;
    3. System.out.println(a==b);
    4. Integer c = 127;
    5. Integer d = 127;
    6. System.out.println(c==d);
    7. Integer e = 128;
    8. Integer f = 128;
    9. System.out.println(e==f);
    10. true
    11. true
    12. false

    equals 对于没有重写equals方法的引用类型的比较和==是一样的,只是String,包装类等重写了equals方法,所以按重写后的规则进行比较,比较的是对象指向的内容是否相等;对于基本数据类型则没有equals方法

    2,原因
    查看Integer源码发现,Integer内部有一个静态变量缓存池IntegerCache,里面声明了一个Integer[]数组,范围-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 e = 128 ,其实就是调用Integer的valueOf(int i)方法进行自动装箱

    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. }

    如果范围不超过-128——127,则从IntegerCache中直接获取Integer对象,如果不在范围内则会new一个新的Integer对象。

    根据==和equals区别可以得到为什么要用equals比较了。

  • 相关阅读:
    Java 16 新特性:record类
    刷题 | 单调栈
    shell脚本
    C# xml、config文件添加自定义节点
    Stages—研发过程可视化建模和管理平台
    边缘人工智能的模型压缩技术
    LeetCode 1004.最大连续1的个数
    Python自动化测试之request库(四)
    【自学前端】我只学这些够吗?好难
    两个版本cuda,如何指定cuda版本教程步骤附带cuda时提示空间不足“Not enough space on parition mounted at /”
  • 原文地址:https://blog.csdn.net/qq_48964306/article/details/128145840