• java中Integer与int装箱拆箱一点收获


     示例代码:

    class BoxIntInteger {
    
        public static void main(String[] args) {
    
            Integer a = new Integer(10111);
            int b = 10111;
            boolean equal1 = a == b;
            boolean equal2 = a.equals(b);
            System.out.println(equal1);
            System.out.println(equal2);
        }
    }
    

      

    反编译字节码:

        public static void main(String args[])
        {
            Integer a = new Integer(10111);
            int b = 10111;
            boolean equal1 = a.intValue() == b;   
            boolean equal2 = a.equals(Integer.valueOf(b));
            System.out.println(equal1);
            System.out.println(equal2);         
        }
    

      

    1:可以看出对于Integer与int使用==比较大小的话,优先Integer拆箱。

    2: 如果使用equals比较大小的话,则int装箱。

    提示:对于Integer与int之间大小比较优先使用equals比较,否则容易出现空指针,例如:

          Integer c= null;
          System.out.println(c==1);
    

      原因:由于Integer需要调用intValue进行拆箱,因而空指针。

    Integer与Integer必须使用equals方法比较,这个就不必解释了。但是通常我们可以看先Integer与Integer之间使用==也可以正确比较,原因是:Integer对于-128到127之间的数字在缓存中拿,不是创建新对象。

    缓存获取数据源码:java.lang.Integer#valueOf(int)

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

     更多关于缓存细节参考:java.lang.Integer.IntegerCache

  • 相关阅读:
    表的相关内容
    数据类型
    mysql入门练习
    mysql入门
    协程
    多进程
    装饰器
    网络编程
    心路历程
    gensim的使用
  • 原文地址:https://www.cnblogs.com/leodaxin/p/9088036.html
Copyright © 2020-2023  润新知