一、继承关系
Byte、Short、Integer、Long、Float、Double 都直接继承抽象父类 Number
,该类提供了将 Number 类型的数据,转换成相对应的基本数据类型的方法。
public abstract class Number implements java.io.Serializable {
public abstract int intValue();
public abstract long longValue();
public abstract float floatValue();
public abstract double doubleValue();
public byte byteValue() {
return (byte)intValue();
}
public short shortValue() {
return (short)intValue();
}
private static final long serialVersionUID = -8742448824652078965L;
}
二、属性 & 构造器
private final int value;
public Integer(int value) {
this.value = value;
}
public Integer(String s) throws NumberFormatException {
this.value = parseInt(s, 10); // 10 为 十进制的意思
}
三、缓存类
private static class IntegerCache {
static final int low = -128;
static final int high; // 127
static final Integer cache[];
四、拆箱 & 装箱
(1)装箱 valueOf
:int -> Integer
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
- 如果 i 的值在
-128 ~ 127
之间,则直接返回缓存类中缓存数组cache
中的值。 - 如果 i > 128,则直接创建一个新的 Integer 返回。
(2)拆箱 intValue
:Integer -> int
public int intValue() {
return value;
}
五、创建案例
Integer i = 10; // Integer i = Integer.valueOf(10); 第一次声明,将 i 放入缓存
Integer j = 10; // 第二次直接从缓存中取
System.out.println(i == j); // true
Integer m = 128; // Integer i = Integer.valueOf(128); 超过 127,直接新建一个对象,不放入缓存
Integer n = 128; // 超过 127,直接新建一个对象,不放入缓存
System.out.println(m == n); // false
int a = 10;
System.out.println(j == a); // true,j 自动拆箱,比较的是基本数据类型
int b = 128;
System.out.println(n == b); // true,n 自动拆箱,比较的是基本数据类型
Integer x = new Integer(66); // 直接创建新对象
Integer y = new Integer(66); // 直接创建新对象
System.out.println(x == y); // false