一、基本数据类型的包装类

byte

Byte

short

Short

int

Integer

long

Long

char

Character

float

Float

doule

Double

boolean

Boolean

其中,int类型的包装类是Integer,char类型的包装类是Character。其他的基本数据类型的包装类,都是在对该基本数据类型的首字母进行大写。

二、包装类的自动装箱与拆箱

自JDK1.5开始,Java提供了自动拆箱与装箱的功能

【1】自动装箱

Integer in = 15;

自动装箱底层依赖的是valueOf(xxx i)方法

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

【2】自动拆箱

public static void main(String[] args) {
         Integer in = new Integer(15);
         int a = in;
     }

自动拆箱底层依赖的是 xxxValue()方法

public int intValue() {
         return value;
     }

补充习题:

public static void main(String[] args) {
		Integer in = 50;
		Integer in2 = 50;
		System.out.println("in == in2 :" + (in==in2));
		Integer in3 = 500;
		Integer in4 = 500;
		System.out.println("in3 == in4 :" + (in3==in4));
		
	}

答案:

in == in2 :true
 in3 == in4 :false

大家是不是觉得很奇怪。重所周知,包装类是类,是引用类型,使用“==”进行比较,比较的不是两个类的地址吗?为什么 会出现in == in2 为true,in3 == in4 为false的情况呢!

让我们看看源码

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

可以看出,如果 i是 大于等于 IntegerCache.low 并且 i 小于等于 IntegerCache.high,就返回cache里的数组变量,否则,就返回一个新的对象。

那么low、high与cache各是什么呢?

首先,IntegerCache是Integer类里的静态内部类(还是私有的),在这个类里low的值是-128,high的值为128,cache为一个大小为256的数组,里面变量包含-128到127之间的数。

所以,我么可以得出,当传入的数在(-128到127)之间,Integer给我们返回的是同一个数,否则就返回一个新的对象。

总结与扩展:

  1. Integer在-128到127之间,自动装箱返回的是同一个对象,超出范围会每一次都创建新的对象.
  2. Byte在-128到127之间,自动装箱返回的是同一个对象
  3. Short在-128到127之间,自动装箱返回的是同一个对象,超出范围会每一次都创建新的对象
  4. Long在-128到127之间,自动装箱返回的是同一个对象,超出范围会每一次都创建新的对象
  5. Float和Double每一次都会创建新的对象
  6. Character在0-127范围内,自动装箱返回的是同一个对象,超出范围会每一次都创建新的对象

三、其他注意点

(1)Number是 Byte Short Integer Long Float Double 的共同父类

(2)对应包装类的静态方法parseXXXX()可以将字符串转换为对应的基本数据类型,譬如parseInt()

(3)包装类的哈希码值是固定的。

Byte Short Integer 直接返回对应基本数据类型值作为哈希码值

其他,是通过一系列算法,得出哈希值。但同一个数得到的结果是一致的