包装类:
引用包装类的原因“
1)因为Java是面向对象编程的,但是基本数据类型没有对象,为了完善面向对象的编程,所以给基本类型添加了包装类。
2)Java中的集合,只允许存储引用数据类型。
除了Integer类型和Character类型之外,其他的都和基本类型一样,但是首字母大写
包装类体系结构图:
学习Integer类:
查阅API:
它的属性有:
package Integer;
public class IntegerTest {
public static void main(String[] args) {
System.out.println("Integer最大值为: "+Integer.MAX_VALUE);
System.out.println("Integer最小值为: "+Integer.MIN_VALUE);
System.out.println(Integer.TYPE);
}
}
查看integer的构造方法:
Integer i2=new Integer(s);
System.out.println(i2);
打印对象没有显示地址,说明重写了toString方法。
Integer i=new Integer(123);
Integer i2=new Integer(123);
System.out.println(i==i2);//false 说明new的两个是不同的对象,执向两个不同的地址
System.out.println(i.equals(i2));//true 说明重写了equlas方法,比较了两个值是否相等
Integer>>>><<<<<int>>>><<<<String 之间互相转换
String string="123";
int i=123;
// int>>>>>Integer
Integer i2=new Integer(3);
// Integer>>>>>int
i=i2.intValue();
// int>>>String
string=String.valueOf(i);
// string>>>>int
i=Integer.parseInt(string);
// Integer>>>String
string=String.valueOf(i2);
// String>>>Integer
i2=Integer.valueOf(string);
自动装箱:基本类型直接赋值给包装类
自动拆箱:包装类直接赋值给基本数据类型
自动装箱是否会在内存里开辟一个空间呢?
Integer i=127;
Integer i2=127;
System.out.println(i==i2);//true
Integer i3=128;
Integer i4=128;
System.out.println(i3==i4);//false
// 自动装箱不开空间的范围是:-128-127,超过了这个值都会重新的开辟一个空间
源码解释:
//Integer中的私有的静态内部类 ,IntegerCache在Integer类第一次被使用时加载到内存,而且只加载一次
private static class IntegerCache {
static final int low = -128;
static final int high; //声明静态常量high
static final Integer cache[]; //声明一个Integer类型的数组,数组的名称为cache
//静态代码块:作用,为类的静态属性赋值
static {
int h = 127;
high = h; //high的值为127
//cache=new Integer[256]; cache这个数组的长度为256
cache = new Integer[(high - low) + 1];
int j = low; //j=-128
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++); //cache[0]=new Integer(-128);
//...
//cache[255]=new Integer(127);
}
private IntegerCache() {}
}