目录
什么是包装类?
Java语言是一个面向对象的语言,但是Java中的基本数据类型却是不面向对象的。基本类型的数据不具备"对象"的特性(没有成员变量和成员方法可以调用),因此,java为每种数据类型分别设计了对应的类,即包装类。
包装类的特点:
- 所有包装类都是final类型,因此不能创建他们的子类。
- 包装类是不可变类,一个包装类的对象自创建后,他所包含的基本类型数据就不能被改变。
八种基本类型对应的包装类:
基本类型 | 包装类 |
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | double |
char | Character |
boolean | Boolean |
八种基本数据类型的包装类:除了char的是Character、int类型的是Integer,其他都是首字母大写
自动拆装箱
JDK自从1.5版本以后,就引入了自动拆装箱的语法,也就是在进行基本数据类型和对应的包装类转换时,系统将自动进行,这将大大方便程序员的代码书写。
自动装箱:将基本数据类型封装为对象类型,来符合java的面向对象的思想。
自动拆箱:将对象重新转化为基本数据类型。
代码演示:
public class demo {
public static void main(String[] args) {
Integer a = 3;
// 自动装箱 编译器执行了 Integer a = Integer.valueOf(3);
int b = a;
//自动拆箱 编译器相当于执行了int b = a.intValue(3);
}
}
.valueOf和intValue方法,通过这两种方法的源码我们会引出一个新的问题:
128陷阱
取值小于128:
Integer a = 1;
Integer b = 1;
System.out.println(a==b);
输出结果:
取值大于等于128:
Integer a = 128;
Integer b = 128;
System.out.println(a==b);
输出结果:
.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 在if语句范围内,从cache缓存中直接取;那么 cache从哪里?cache来自于Integer中的IntegerCache静态类,在这个类中定义了低点low,高点high;组成了cache数组,数组范围(-128,127),所以当两个Integer类型赋值不在这个范围内,两数比较是否相等返回false
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() {}
}
以上是我个人对包装类知识的见解,不足之处欢迎补充,下篇讲讲类型转换