美文网首页
Integer详解

Integer详解

作者: 无可奈何丶 | 来源:发表于2019-05-24 15:48 被阅读0次

    说起来今天有个同事问了我这样一个问题

    Integer i = new Integer(128);
    Integer ii =new Integer(128);
    System.out.println(i == ii);
    

    问false还是true嗯?我当然肯定的给出了结果==比较值两个值都是128肯定是相等的啊。结果是false!让我产生了查看源码的冲动。结果发现了如下代码

    private static class IntegerCache {
            static final int low = -128;
            static final int high;
            static final Integer cache[];
    
            static {
                // high value may be configured by property
               //可以配置该值,否则默认就为127
                int h = 127;
                String integerCacheHighPropValue =
                    sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
                if (integerCacheHighPropValue != null) {
                    try {
                        int i = parseInt(integerCacheHighPropValue);
                        i = Math.max(i, 127);
                        // Maximum array size is Integer.MAX_VALUE
                        //如果有值赋值到h
                        h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
                    } catch( NumberFormatException nfe) {
                        // If the property cannot be parsed into an int, ignore it.
                    }
                }
               //默认127
                high = h;
               //cache数组的长度为 127-(-128)+1=255
                cache = new Integer[(high - low) + 1];
                int j = low;
               //循环从-128-127存入到cache中
                for(int k = 0; k < cache.length; k++)
                    cache[k] = new Integer(j++);
                // range [-128, 127] must be interned (JLS7 5.1.7)
               //断言最高不能超过127
                assert IntegerCache.high >= 127;
            }
    
            private IntegerCache() {}
        }
    
     public static Integer valueOf(int i) {
            //判断i>=最小值并且小于最大值,如果符合直接从缓存中返回
            if (i >= IntegerCache.low && i <= IntegerCache.high)
                return IntegerCache.cache[i + (-IntegerCache.low)];
          //不符合就重新new一个新的对象
            return new Integer(i);
        }
    
    Integer.png

    通过断点可以明显的看到是两个不同的对象。711和712

    IntegerCache 静态内部类,有静态代码块在程序初始化时就已经执行了,通过去查询是否有配置high,如果没有的话默认最高值为127,给定一个长度为(high-low)+1cache数组,将-128-127之间的数字全部存入到该数组作为缓存存在。Integer在声明时会自动调用valueOf()方法。所以结果显而易见。若初始化的值>127||<-128就会重新声明一个对象,那么这样的话就产生了两个不同的对象,==自然是false。

    自动装箱,自动拆箱(Integer,String)。

    自动装箱自动把基本数据类型封装为对象类型。

    Integer num = 10;
    //本质上Integer是一个对象不可以直接赋值为基本数据类型。所以这一步骤就是自动装箱。
    Integer nums=10;
    
    String s ="abc";
    //String也同理
    String ss = new String("abc");  
    

    自动拆箱是自动把对象类型封装为基本类型

    Integer num = 10;
    //自动吧Integer类型转换为基础类型。
    int nums = num;
    

    相关文章

      网友评论

          本文标题:Integer详解

          本文链接:https://www.haomeiwen.com/subject/ghibzqtx.html