简单一文了解Java的包装类

1.基本数据类和包装类直接的对应关系

包装类 基本数据类型
Integer int
Short short
Long long
Byte byte
Float float
Double double
Character char
Boolean boolean

基本就是类型的首字母大写,除了 Integer 和 Character

2. 包装类的使用装箱和拆箱(boxing&&unboxing)

2.1 自动的拆装箱

    public static void main1(String[] args) {
    
    
        /*
        把基本数据类型转为对应的包装类型
        装箱/装包
        1.自动装箱
        2.显示装箱
         */
        Integer a = 10;
        Integer b = new Integer(10);
        /*
        把包装类转为基本数据类型
        1.自动拆箱
        2.显示拆箱
         */
        int c = a;
    }

调用反汇编工具:javap -c 字节码文件名
在这里插入图片描述
我们从反汇编中得知

  1. 装箱调用的 Integer.valueOf 方法
  2. 拆箱调用的 .intValue 方法

分析装箱过程
我们进入 valueOf 查看
在这里插入图片描述

我们发现 valueOf 只能穿入 String , int 类型的数据。其中 valueOf(String, int) 中的 int 代表的是进制数, 一般不常用这个方法

拆箱过程
在这里插入图片描述

没有加 static 修饰

2.2 手动的拆装箱

    public static void main(String[] args) {
    
    
        Integer a = Integer.valueOf(1);// 手动装箱
        int b = a.intValue();// 手动拆箱
        short s = a.shortValue();
        long l = a.longValue();
        byte b = a.byteValue();
        double d = a.doubleValue();
        float f = a.floatValue();
    }

总结

  1. 装箱: 包装类.valueOf 方法
  2. 拆箱: int/float/double/short/byte/long+ValueOf
  3. 没有 .boolValueOf, .charValueOf.StringValueOf 方法

取值范围

     Integer x = 127;
     Integer y = 127;
     System.out.println(x == y);
     System.out.println("==========");
     Integer xx = 128;
     Integer yy = 128;
     System.out.println(xx == yy);

true
==========
false

我们查看一下之前的 valueOf 源码
在这里插入图片描述

有个 [-128, 127] 这样的一个数据范围

我们查看 low
在这里插入图片描述
自此我们就发现了 为什么127为true而128为false的根本原因

catch数组的取值范围
在这里插入图片描述

public static Integer valueOf(int i) {
    
    
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

解释

  1. 首先看传入进来的值是否在 catch 数组区间内
  2. 如果在区间,则返回catch数组中的值 catch[index] , 值和值用 "=="比较当然会 true
  3. 如果不在 catch 数组区间, 则返回一个 new对象, 在用 "==" 比较, 就是比较的引用地址,结果当然是不相等为 false

反思:catch缓存数组有何作用?

提高效率的.实例化对象, 是需要消耗资源的.
看视频: 在线观看一边看一边缓存,提高看视频的流畅度

Guess you like

Origin blog.csdn.net/weixin_45364220/article/details/120575114