`
jilen
  • 浏览: 96654 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

装箱和拆箱和ValueOf以及XXXValue -- Java语法糖(Syntax sugar)

    博客分类:
  • java
阅读更多

自动装箱拆箱发生在基本类型和其包装型互操作的时候。

以前一直不知的拆箱和装箱是valueOf和xxValue的别名。是语法糖的一种

 

 

public static void main(String[] args) {
		Integer i = 10;
		Integer j = 10;
		System.out.println(j == i); //(1) true update1.1 如果i是反序列化回来的,那么不论值为多少,都不能==,因为反序列会生成新对象,不会调用valueOf了

		i = 10000;
		j = 10000;
		System.out.println(j == i); //(2) false

		i = new Integer(10000);
		System.out.println(i == 10000); //(3) true
		System.out.println(10000 == i); //(4)  true
		System.out.println(i == 10000L);//(5) true

	}

 

 

(1)处的结果是 true。

(2)处的结果是false。

(3)处的结果是true,true,true

 

(1),(2)处的结果不同让人惊讶。i = 10;和i=10000;发生了自动装箱,编译器自动编译成 Integer.valueOf(10)和Integer.valueOf(10000)。看看这个方法的实现。

 

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

 

看到某些Integer对象是有缓存的,范围是-128,到high。

再看看IntegerCachestatic final int high;

        static final Integer cache[];

        static {
            final int low = -128;

            // high value may be configured by property
            int h = 127;
            if (integerCacheHighPropValue != null) {
                // Use Long.decode here to avoid invoking methods that
                // require Integer's autoboxing cache to be initialized
                int i = Long.decode(integerCacheHighPropValue).intValue();
                i = Math.max(i, 127);
                // Maximum array size is Integer.MAX_VALUE
                h = Math.min(i, Integer.MAX_VALUE - -low);
            }
            high = h;

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

    high默认是127,可以通过integerCacheHighPropValue

调整,看看这个属性的说明

 

 /**
     * Cache to support the object identity semantics of autoboxing for values between 
     * -128 and 127 (inclusive) as required by JLS.
     *
     * The cache is initialized on first usage. During VM initialization the
     * getAndRemoveCacheProperties method may be used to get and remove any system
     * properites that configure the cache size. At this time, the size of the
     * cache may be controlled by the vm option -XX:AutoBoxCacheMax=<size>.
     */

    // value of java.lang.Integer.IntegerCache.high property (obtained during VM init)
    private static String integerCacheHighPropValue;

 可以通过该参数调整缓存的范围  -XX:AutoBoxCacheMax=<size>

 

3,4,5处发生拆箱,编译之后其实调用了intValue,或者longValue。获得的是基本类型。

 

 

总结: 两个包装类型的值比较,最好不要用 ==

 

2
2
分享到:
评论
2 楼 Rejoy 2012-08-11  
正想写这个的   已经被你写了 呵呵
1 楼 chenjingbo 2011-10-28  
说的很仔细.. ..不错

相关推荐

Global site tag (gtag.js) - Google Analytics