Integer和int——Java包装器

来源:互联网 发布:双色球选红球算法 编辑:程序博客网 时间:2024/06/04 19:36

1、包装器

在Java中,所有基本类型都有一个与之对应的类。如int类型与Integer类相对应;double类型与Double类相对应等。这些类被称为包装器(wrapper),或者叫对象包装器。Java有8种基本类型,有9个包装器,分别为:Integer、Long、Short、Byte、Double、Float、Character、Boolean以及Void。前6个类都派生于一个公共的超类Number。

包装器是不可变的。也就是说构造好了包装器,就不能更改包装在其中的值。此外,包装器类是final类,无法定义它们的子类。

2、装箱

概念:自动将基本数据类型转换为对应包装器对象

Integer a=10; 等价于: Integer a=Integer.valueOf(10); 等价于:Integer a=new Integer(10);

3、拆箱

概念:自动将包装器对象转换为对应的基本数据类型

Integer i=new Integer(5);int b=i;等价于:Integer i=new Integer(5);int b=i.intValue();


4、说明

装箱和拆箱是编译器认可的,而不是虚拟机。编译器在生成类的字节码的同时,插入必要的方法调用;虚拟机只是执行这些字节码。

5、关于包装器的==和equals()方法

5.1 valueOf方法的源代码

public static Integer valueOf(int i) {        if (i >= IntegerCache.low && i <= IntegerCache.high)            return IntegerCache.cache[i + (-IntegerCache.low)];        return new Integer(i);    }
当参数i为在区间[-128,127]上的int数值时,就返回缓存中的Integer对象,i不在这个区间内,就返回一个新创建的Integer对象。

5.2 关于==

1)当==符号比较基本数据类型时,比较的是它们的值。

2).当==符号计较对象时,比较的是它们是否指向同一个区域(即是否有相同的引用)。

3).当==操作符的两边,一个操作数是基本数据类型,另一个是对象时,则会将对象进行拆箱,从而变成两个基本数据类型进行值的比较。

Test test1=new Test();Test test2=new Test();Test test3=test2;System.out.println(test1==test2);//falseSystem.out.println(test2==test3);//true

5.3 包装器的==


Integer aInteger=new Integer(100);Integer aInteger2=Integer.valueOf(100);Integer bInteger=100;Integer cInteger=100;Integer dInteger=200;Integer eInteger=200;System.out.println(aInteger==aInteger2);//false,一个在堆区,一个在缓存中System.out.println(aInteger==bInteger);//false,同上System.out.println(aInteger2==bInteger);//true,同在缓存中System.out.println(bInteger==cInteger);//true,同上System.out.println(dInteger==eInteger);//false,超出[-128,127]为堆上不同的对象


6.其他包装器的valueOf

6.1 Long 类

public static Long valueOf(long l) {        final int offset = 128;        if (l >= -128 && l <= 127) { // will cache            return LongCache.cache[(int)l + offset];        }        return new Long(l);}
6.2 Short类

public static Short valueOf(short s) {        final int offset = 128;        int sAsInt = s;        if (sAsInt >= -128 && sAsInt <= 127) { // must cache            return ShortCache.cache[sAsInt + offset];        }        return new Short(s);    }

6.3 Double类

public static Double valueOf(String s) throws NumberFormatException {     return new Double(parseDouble(s));}

其他类类似。










1 0
原创粉丝点击