前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java中Integer的变量比较源码解析

Java中Integer的变量比较源码解析

作者头像
程序新视界
发布2022-11-30 16:08:26
6890
发布2022-11-30 16:08:26
举报
文章被收录于专栏:丑胖侠

面试例子:

代码语言:javascript
复制
public static void main(String arg[]){  
     Integer a=3;  
     Integer b=3;  
     System.out.println(a==b);  
     System.out.println(a.equals(b));  
     a=3333;  
     b=3333;  
     System.out.println(a==b);  
     System.out.println(a.equals(b));  

 } 

此程序打印出来的结果分别为:true,true,false,true。那么为什么会出现这种结果呢?

原因分析

我们要知道当给一个Integer对象赋一个int值时,Integer的valueOf方法会被调用。那么,我们看看Integer的valueOf方法到底做了些什么。源码如下:

代码一:

代码语言:javascript
复制
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);
}

代码二:

代码语言:javascript
复制
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
        int h = 127;
        String integerCacheHighPropValue =
            sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
        if (integerCacheHighPropValue != null) {
            int i = parseInt(integerCacheHighPropValue);
            i = Math.max(i, 127);
            // Maximum array size is Integer.MAX_VALUE
            h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
        }
        high = h;

        cache = new Integer[(high - low) + 1];
        int j = low;
        for(int k = 0; k < cache.length; k++)
            cache[k] = new Integer(j++);
    }

    private IntegerCache() {}
}

通过代码一我们可以看出,当valueOf传入的值在IntegerCache.low和IntegerCache.high之间时,Integer被赋的值将从IntegerCache.cache数组中获得,也就是通过缓存中获得。

再看代码二,IntegerCache.low为常量-128。而IntegerCache.high如果在启动JVM时没有指定-XX:AutoBoxCacheMax参数,默认为127。综合两段代码,我们可以知道,在默认情况下,在-128到127之间的数据在赋值时会从缓存中获得。

结论

因此,在-128到127之间的数据多次获得的均为同一个对象,而超出这个范围的数据将会创建一个新的对象,只能通过equals方法比较的才是对象的值。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2015-09-01,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 面试例子:
  • 原因分析
  • 结论
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档