什么是包装类
java是面向对象编程的,但是基本数据类型是没有对象的。
针对每一个基本数据类型,java都设置了一个对象。
byte -----> Byte short -----> Short int -----> Integer long -----> Long char -----> Character float -----> Float double -----> Double boolean -----> Boolean
基本数据类型与包装类的区分
int是基本数据类型,而Integer是一个类。
int类型的数据初始化为0;
Integer类型的数据初始化为null。
包装类的自动拆装箱
基本数据类型与其对应的包装类是等价的.
public class Main {
public static void main(String[] args) {
int a = 10;
Integer b = a;
System.out.println(b);
}
}
自动装箱
基本数据类型 -----> 包装类
例如:int -----> Integer
Integer num1 = 10;
//----->JVM将其编译为:
Integer num2 = Integer.valueOf(10);
上述二者的效果是等价的,后者为自动装箱。
public class Main {
public static void main(String[] args) {
int a = 10;
Integer b = 10;
System.out.println(b.equals(a));
}
}
equals()方法要求传Object类型的数据,a自动装箱。
自动拆箱
包装类 -----> 基本数据类型
例如:Integer -----> int
Integer num1 = Integer.valueOf(10);
int num2 = num1;
Integer属于类,Integer类型的数据应该在堆内存中开辟内存空间。
public class Main {
public static void main(String[] args) {
int a = 10;
Integer b = 10;
System.out.println(a == b);
}
}
public class Main {
public static void main(String[] args) {
int a = 10;
Integer b = new Integer(10);
System.out.println(a == b);
}
}
包装类用“==”和基本数据类型比较时会自动拆箱。
128陷阱
public class Main {
public static void main(String[] args) {
Integer num1 = 100;
Integer num2 = 100;
System.out.println(num1 == num2);
Integer num3 = 128;
Integer num4 = 128;
System.out.println(num3 == num4);
}
}
valueOf()方法
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
当传入的数据不在指定范围内,会在堆内存中开辟一块新的内存空间。对于引用数据类型而言,”==“比较地址是否相同。
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() {}
}
catch是一个数组,其长度为256,储存的数据范围是[-128,127]。当传入的数据在指定范围之内,则比较数据在catch数组中的位置。若不在catch数组所能承受的范围之内,则重新开辟内存空间用于存储当前数据。