Java的包装器类型

来源:互联网 发布:vb.net连接数据库 编辑:程序博客网 时间:2024/05/16 09:44

首先是我在一篇文章里看到的:

Integer a=1000;

Integer b=1000;

System.out.println(a==b);


上面这些代码,对于一些知道 ''=='' 含义的人都明白,这个结果是False。因为他们是不同对象!


Integer c=100;

Integer d=100;

System.out.println(c==d);


相同的代码,不知道又有多少人认为是False?  但悲剧的是True!!!


对,但是这篇文章没有讲为什么会不同,只说了-128到127才会为true,提到这个就不得不说一下Java的包装器类型了。

基本类型的包装器类型分别是:

boolean Boolean

char Character

byte Byte

short Short

int Integer

long Long

float Float

double Double

void Void


首先学过Java的人都知道,这两者肯定是不一样的,就是基本类型和对象的区别嘛,一个栈一个堆。


java se5的自动包装功能将自动地将基本类型转换为包装器类型:

Character ch = 'x';

Integer a = 3; 这是自动包装

并可以反向转换:

char c =ch;

int i = new Integer(2); 这是自动拆包


自动装包和拆包的具体过程都由编译器完成。

比如以Integer为例的自动装包: Integer a=3; 其实编译器调用的是static Integer valueOf(int i)这个方法

就是这样:Integer a=3——>Integer a=Integer.valueOf(3);

而这个方法就是导致上面一个true一个false的原因,代码如下:

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

首先是一个assert断言,这个IntegerCache就是一个辅助的static类,IntegerCache.low的值就是-128,IntegerCache.high就是127;好了,这样就可以解释上面的情况了,当在-128和127之间时,实际上调用这个方法返回的全部都是IntegerCache这个类里事先存放好的对象,意思就是不论Integer  a还是b的初始化,只要值一样,返回的都是同一个对象,所以可以用==;反之如果不在区间里,就会在堆里新建一个对象。


上面这种写法是Javase5之后的,在5之前没有IntegerCache这个类,直接用了一个size为256名叫SMALL_VALUE(好像是这个名字吧我记不太清了)的数组,存放-128到127之间的所有整型。不过对功能来说都一样。


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

可以看到一点,low变量直接是-128,但是high变量是根据不同VM的配置来决定的。


下面是character里的valueof方法:

    public static Character valueOf(char c) {        if (c <= 127) { // must cache            return CharacterCache.cache[(int)c];        }        return new Character(c);    }


IntegerCache初始化后内存中就有Integer缓冲池cache[]了
java使用该机制是为了达到最小化数据输入和输出的目的,这是一种优化措施,提高效率 
其他的包装器: 
Boolean: (全部缓存) 
Byte: (全部缓存) 

Character ( <=127 缓存) 
Short (-128~127 缓存) 
Long (-128~127 缓存) 

Float (没有缓存) 
Doulbe (没有缓存) 


这几个在源码里都写的比较清楚了。


本文部分参考:http://bravingboy.diandian.com/post/2012-02-01/40028921631
原创粉丝点击