一起来学Java——包装类

一起来学Java——包装类

在前一篇的泛型知识中我们了解到,通过泛型,可以让不同的类型实现相同的操作。其中利用的原理是Object可以指向任意类型的类。但是像int,float,byte,short,long都是基本数据类型,不是类。所以为了解决这个问题,我们就引入包装类这个概念。

包装类都有那些?

基本数据类型包装类
byteByte
shortShort
intInteger
floatFloat
doubleDouble
booleanBoolean
charCharacter

注意:

  1. 包装类只是针对基本数据类型,不包含String
  2. int和char比较特殊,int——Integer,char——Character。除了这两个都是相应的首字母大写

包装类的用途

除了上面的泛型需要用到包装类,包装类还有那些用途呢?

可以用作数据间的转化

public class Wrapper {
    public static void main(String[] args) {
        String string="12345";
        int ret=Integer.valueOf(string);
        System.out.println(ret);
    }
}

包装类的拆包和装包

隐式

直接将数字或者字符赋予包装类就是隐式

public static void main(String[] args) {
    Integer integer=111;//隐式装包
    int a=integer;//隐式拆包
    System.out.println(a);
}
image-20220112163645995

通过javap -c反汇编之后,我们发现,上面的隐式装包,编译器背后调用了valueof,隐式拆包,编译器背后调用了intValue

所以,不正面调用上面的两个函数的就是隐式,故显式的就是直接调用

显式

直接调用相关的函数即可

Integer integer=Integer.valueOf(111);//显式装包
Integer integer1=new Integer(111);//显式装包,直接new一个数字

//显示拆包:直接调用intvalue
int ret=integer.intValue();
float ret2=integer.floatValue();
关于valueOf
public static void main(String[] args) {
 	//1
    Integer integer=135;
    Integer integer1=135;
    //2
    Integer integer2=new Integer(12);
    Integer integer3=new Integer(12);
    //3
    Integer integer4=12;
    Integer integer5=12;
    System.out.println(integer==integer1);//false
    System.out.println(integer2==integer3);//false
    System.out.println(integer4==integer5);//true;
}

上面的三组,第二组是最容易去理解的,因为每一个new出来的对象的地址都是不同的,都是一个单独的个体。

但是,为什么1,2组有着两个相反的结果呢?

我们就要来看一下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处于low(-127)到high(128)之间的时候,就直接从cache数组中拿元素。但是当不再这个位置的时候就要new一个新的对象了,由此就可以解释1,3的不同。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值