基本数据类型和包装类

1、包装类

Java是面向对的语言,很多地方都需要使用对象而不是基本数据类型。比如,在集合类中,我们是无法将 int 、double 等类型放进去的。因为集合的容器要求元素是 Object 类型。8种基本数据类型却不是面向对象的,所以为了使用方便为每一种数据类型专门在java.lang包下提供了对应的包装类。在这八个类名中,除了 Integer 和 Character 类以后,其它六个类的类名和基本数据类型一致,只是类名的第一个字母大写即可。


基本数据类型和包装类

2、拆箱、装箱

装箱:将基本数据类型转换成对应的包装类对象使用。Integer integer=1;

拆箱:将包装类转换成对应的基本数据类型来使用。int i=integer;

装箱例子:

int i=1;

list.add(i);

//list只能放Integer 对象,装箱Integer integer=1; list.add(integer);

开箱例子:

Integer i = new Integer(10);

int a=i+1;

//对象无法做加法运算,拆箱10=i;a=10+1;


3、自动

为什么基本数据类型能自动做到开箱和装箱。以(int举例)原因在于Integer内部自动调用了valueOf(Integer a)方法用于装箱和Intvalue()方法拆箱。

源码参考如下:

//自动拆箱

public int intValue() {

        return value;

    }

Integer a = new Integer(10);

a.Intvalue();

//自动装箱

public Integer(int value) {

        this.value = value;

    }

Integer a=new Integer();

a.valueOf(10);

4、包装类的缓存机制。

public static Integer valueOf(int i) {

        if (i >= IntegerCache.low && i <= IntegerCache.high)

            return IntegerCache.cache[i + (-IntegerCache.low)];

        return new Integer(i);

    }

  缓存机制发生在装箱的过程,Character, 范围是 0 到 127、Byte、Short、Integer、Long固定缓冲区为(-128,127)。Integer可以通过-XX:AutoBoxCacheMax=size 修改更改最大值 127。这个缓存机制作用就是为了避免对象重复创建,在缓存区中相同的值可用同一对象表示。

总结

a、包装类就是为了让基本数据类型能够作为对象来使用。

b、装箱就是基本数据类型变成包装类类型,拆箱就是将包装类类型变成基本数据类型

c、能够做到自动是因为包装类提供了对应的方法。valueOf 方法自动装箱,XXXValue方法自动拆箱。

d、缓存机制发生在自动装箱过程,作用就是为了避免包装类对象重复创建。

你可能感兴趣的:(基本数据类型和包装类)