探究Integer底层

现在有这样两组代码:

第一组

        Integer s1=127;
        Integer s2=127;
        if(s1==s2){
            System.out.println("s1==s2");
        }else {
            System.out.println("s1!=s2");
        }

输出是s1==s2;

第二组

        Integer s1=128;
        Integer s2=128;
        if(s1==s2){
            System.out.println("s1==s2");
        }else {
            System.out.println("s1!=s2");
        }

输出是s1!=s2;

注意,程序代码不过是将127改为128,但执行结果明显不一样,这是为何?以上例子来说,创建Integer实例会使用Integer.valueOf(),所以我们要知道怎么使用Integer.valueOf()来建立Integer实例。查下jdk文件夹src.zip中的java/lang文件中的Integer.java,我们会看到valueOf()的内容:

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);
        }

这段代码的意思是如果int i 在IntegerCache.low与IntegerCache.high之间,那就看看前面缓存中cache中有没有这个值,如果有这个值的话就直接返回,否则就返回一个新的Integer实例。IntegerCache.low的默认值是-128,IntegerCache.high的默认值是127。

看了上面一段,大家大概了解一点了吧,

        Integer s1=127;
        Integer s2=127;

执行到s1的时候,由于s1 127在-128和127之前,所以建立的Integer实例会放到缓存中,执行到s2的时候,由于s2的值也是127,所以会直接返回缓存中的已建立的Integer实例,所以s1和s2参考的是同一个Integer实例,使用==会返回true

        Integer s1=128;
        Integer s2=128;

执行到s1的时候,由于s1 128不在-128和127之前,所以建立的Integer实例不会放到缓存中,执行到s2的时候,s2也会直接创建一个新的Integer实例,s1和s2不是同一个Integer实例,所以使用==会返回false

注意:这种情况,前提条件下是在启动JVM时,不更改IntegerCache.high的默认值!!!!

猜你喜欢

转载自blog.csdn.net/qq_38146131/article/details/81949506
今日推荐