包装类
Java是面向对象的语言,但在基本数据类型却不是对象,为了方便和解决这一不足,Java提供了与八种基本数据类型相对应的包装类
八种基本数据类型与对应的包装类如下
基本数据类型 | 包装类 |
---|---|
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
boolean | Boolean |
char | Character |
基本数据类型、包装类和String类的相互转换
基本数据类型转包装类
//方式一:调用包装类的构造器
Integer num1 = new Integer(1);
//方式二:调用包装类的valueOf方法
Integer num2 = Integer.valueOf(1);
包装类转基本数据类型
根据需要的数据类型调用包装类对象中相应的xxxValue方法
Integer num1 = new Integer(1);
int num2 = num1.intValue();
double num3 = num1.doubleValue();
String类转基本数据类型
使用基本数据类型对应的包装类中的parsexxx方法
String str = "123";
int num = Integer.parseInt(str);
自动装箱与自动拆箱
jdk 5.0新特性
自动装箱:自动的将基本数据类型转换为包装类
原理:自动调用了包装类的valueOf方法
Integer num = 1;
//等价于
Integer num = Integer.valueOf(1);
自动拆箱
原理:自动调用了包装类对象的xxxValue方法
Integer num1 = 1;
int num2 = num1;
//等价于
int num3 = num1.intValue();
缓存机制
java 包装类的缓存机制,是在Java 5中引入的一个有助于节省内存、提高性能的功能,只有在自动装箱时有效
先看案例
Integer num1 = 1;
Integer num2 = 1;
System.out.println(num1 == num2);
结果为true
我们都知道两个对象进行比较,比较的是内存地址,上面的两个对象并不是同一个对象,但比较后的结果却是true
自动装箱的底层是自动调用了valueOf方法,我们先看该方法的源码
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和Integer.high之间,就从IntegerCache中获取
再来看一下InegerCache类
该方法定义在包装类的内部,且只有Byte、Short、Integer、Long、Character和Boolean中存在
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer cache[];
static {
// high value may be configured by property
int h = 127;
String integerCacheHighPropValue =
sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
try {
int i = parseInt(integerCacheHighPropValue);
i = Math.max(i, 127);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
} catch( NumberFormatException nfe) {
// If the property cannot be parsed into an int, ignore it.
}
}
high = h;
cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
// range [-128, 127] must be interned (JLS7 5.1.7)
assert IntegerCache.high >= 127;
}
private IntegerCache() {}
}
默认范围为 -128和127之间,范围的最大值可以通过java.lang.Integer.IntegerCache.high设置,通过for循环将范围内的数据实例化为Integer对象放到cache数组里
现在再来测试一下
Integer num1 = 128;
Integer num2 = 128;
System.out.println(num1 == num2);
结果为false
原因在于使用自动装箱时,所创建的对象的大小超过-128和127之间,所以不会使用缓存