java基础之包装类和基本类型

1.包装类对象是不可变的.

2.== ,在包装类和基本类型使用== 比较的时候,包装类会自动拆装为基本类型再比较

3.小于等于<=127 的boolean,byte,char,和介于-128~127之间的short 和int 被包装到固定地址的包装类对象中.但如果是new 出来的包装对象则会被分配新的地址,不再是固定的.

如:

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Integer a = new Integer(1);
        Integer b = new Integer(1);
        int c=1;
        Integer d = 1;
        Integer e=1;
        System.out.println("a==b:"+(a==b));
        System.out.println("d==e:"+(d==e));
        System.out.println("a==c:"+(a==c));
        System.out.println("a==e:"+(a==e));
        System.out.println("c==e:"+(c==e));
    }
结果是:
    a==b:false
    d==e:true
    a==c:true
    a==e:false
    c==e:true

4.在声明<=128 或者 -128~127 的时候是分配固定的包装类,而包装类的方法Integer valueOf(String s) 也是 分配固定的包装类对象.源码如下:

 public static Integer valueOf(int i) {  
    final int offset = 128;  
    if (i >= -128 && i <= 127) { // must cache  
        return IntegerCache.cache[i + offset];  
    }  
        return new Integer(i);  
    }

java 这样设计或许是因为 这个范围的值是用的最多的.

posted @ 2015-08-15 11:00  predisw  阅读(179)  评论(0编辑  收藏  举报