Java 包装类的自动拆装箱与相等判断
2018-05-06 本文已影响15人
一片彬心在玉壶
缘起:
基本类型的包装类的使用中经常会遇到自动拆箱和自动装箱,有时候会因为操作不规范导致一些意想不到的问题。
注意
在使用包装类的时候要注意一下事项
-
用基本类型来赋值给包装类的时候,会有自动装箱
调用相关包装类的valueOf方法。[附一,自动装箱代码反编译]
-
判断是否相等时使用equal时,会自动拆箱,使用基本值 == 判断。
-
尽量不要使用 == 判断,需要注意以下情况:
- 包装类会有相应的基本类的缓存数组,一般范围是在-128 - 127,如果有的话会返回缓存的对象。
- 范围外的都是新建的对象。
- 不包含Float、Double
以下Byte的相关源码
Byte
//自动装箱,调用内部类缓存
public static Byte valueOf(byte b) {
final int offset = 128;
return ByteCache.cache[(int)b + offset];
}
// 静态内部类,包含相应包装类数组,已事先创建好对象
private static class ByteCache {
private ByteCache(){}
static final Byte cache[] = new Byte[-(-128) + 127 + 1];
static {
for(int i = 0; i < cache.length; i++)
cache[i] = new Byte((byte)(i - 128));
}
}
//equal对比,如果是包装类,就使用基本类相等
public boolean equals(Object obj) {
if (obj instanceof Byte) {
return value == ((Byte)obj).byteValue();
}
return false;
}
其他包装类类似。
[附二,相应包装类的JDK 源码]
不包括 Float、Double
附一,自动装箱代码反编译
使用javap -c 命令查看相应代码的反编译指令
public void testEqual() {
Integer i1 = 1;
Integer i2 = 1;
System.out.println(i1 == i2);
}
javap -c 相应字节码,得出以下反编译结果
public void testEqual();
Code:
0: iconst_1 // int类型 1 入操作数栈
1: invokestatic #2 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer; 自动装箱
4: astore_1 // 栈顶元素赋值 位置1变量
5: iconst_1 // int 1 入栈
6: invokestatic #2 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
9: astore_2 // 栈顶元素赋值 给位置2变量
10: getstatic #3 // Field java/lang/System.out:Ljava/io/PrintStream;
13: aload_1 //从位置为1的局部变量中取出元素int类型的1压入栈
14: aload_2 //从位置为2的局部变量中取出元素int类型的1压入栈
15: if_acmpne 22
18: iconst_1
19: goto 23
22: iconst_0
23: invokevirtual #4 // Method java/io/PrintStream.println:(Z)V
其他包装类的JDK 源码
//Character
public static Character valueOf(char c) {
if (c <= 127) { // must cache
return CharacterCache.cache[(int)c];
}
return new Character(c);
}
private static class CharacterCache {
private CharacterCache(){}
static final Character cache[] = new Character[127 + 1];
static {
for (int i = 0; i < cache.length; i++)
cache[i] = new Character((char)i);
}
}
public boolean equals(Object obj) {
if (obj instanceof Character) {
return value == ((Character)obj).charValue();
}
return false;
}
//Short
public static Short valueOf(short s) {
final int offset = 128;
int sAsInt = s;
if (sAsInt >= -128 && sAsInt <= 127) { // must cache
return ShortCache.cache[sAsInt + offset];
}
return new Short(s);
}
private static class ShortCache {
private ShortCache(){}
static final Short cache[] = new Short[-(-128) + 127 + 1];
static {
for(int i = 0; i < cache.length; i++)
cache[i] = new Short((short)(i - 128));
}
}
public boolean equals(Object obj) {
if (obj instanceof Short) {
return value == ((Short)obj).shortValue();
}
return false;
}
//Integer
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() {}
}
public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}
//Long
public static Long valueOf(long l) {
final int offset = 128;
if (l >= -128 && l <= 127) { // will cache
return LongCache.cache[(int)l + offset];
}
return new Long(l);
}
private static class LongCache {
private LongCache(){}
static final Long cache[] = new Long[-(-128) + 127 + 1];
static {
for(int i = 0; i < cache.length; i++)
cache[i] = new Long(i - 128);
}
}
public boolean equals(Object obj) {
if (obj instanceof Long) {
return value == ((Long)obj).longValue();
}
return false;
}