1、为什么要有包装类
- 数值之间要自由转换
- java万物皆对象
//基本类型及其包装类
byte ---------------------> Byte
short ---------------------> Short
int ---------------------> Integer
long ---------------------> Long
float ---------------------> Float
double ---------------------> Double
boolean ---------------------> Boolean
char ---------------------> Character
2、什么是包装类
Integer c1= 11; // 自动装箱的过程
// Integer c1 = Integer.valueOf(11); // 自动装箱的过程
int a = c1; // 自动拆箱
// int a = Integer.intValue():
public static Integer valueOf(int i) {
if (i >= -128 && i <= 127)
return IntegerCache.cache[i + (-IntegerCache.low)];// 如果我们定义的数据在 -128 到 127 之间我们返回的是cache数组当中的一个地址
return new Integer(i);// 如果我们定义的数据不在-128 到 127 之间我们返回的是重新创建的一个Integer类型的对象的地址
}
public static void main(String[] args) {
int a = 10;
int b = 10;
Integer a1 = 10;
Integer b1 = 10;
Integer a2 = new Integer(10);
Integer b2 = new Integer(10);
System.out.println(a == b);//基本类型==比较的是值 true
System.out.println(a1 == b1);//应用类型 ==比较地址 true
System.out.println(a2 == b2);//在堆中开辟的地址不同,false
System.out.println(a1 == a); //在128范围内,a1=a true ==判断涉及自动拆箱
System.out.println(a1.equals(a));//true 自动装箱过程 自动转型int-->interger-->object
System.out.println(a1 == a2);//地址不同 false
System.out.println(a == a2);// 自动拆箱 true ==a2自动拆箱
}