Integer和int——Java包装器

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);//false
System.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));
}

其他类类似。










  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值