本文最后更新于 2 分钟前,文中所描述的信息可能已发生改变。
基本类型与包装类型
Initial Type and Package Type
基本类型 | 包装类型 | 大小(字节) | 范围 | 是否实现缓存机制 |
---|---|---|---|---|
byte | Byte | 1 | -128 ~ 127 | 是 |
short | Short | 2 | -32768 ~ 32767 | 是 |
int | Integer | 4 | -2147483648 ~ 2147483647 | 是 |
long | Long | 8 | -9223372036854775808 ~ 9223372036854775807 | 是 |
float | Float | 4 | 1.4E-45 ~ 3.4028235E38 | 否 |
double | Double | 8 | 4.9E-324 ~ 1.7976931348623157E308 | 否 |
char | Character | 2 | 0 ~ 65535 | 是 |
boolean | Boolean | 1 | true/false | 是 |
不变类
Immutable Class
包装类型是不可变类,一旦创建对象,对象的值就不能被改变。
Integer
类的实现如下:
java
public final class Integer extends Number implements Comparable<Integer> {
private final int value;
public Integer(int value) {
this.value = value;
}
public int intValue() {
return value;
}
// ...
}
tip提示
不可变性(Immutability) 是指一旦对象创建后,其状态就不能被修改。对于不可变对象,任何看似改变对象状态的操作,实际上都会返回一个新的对象。
缓存机制
Cache Mechanism
Java 中的包装类型,采用缓存池机制减少内存消耗和提高性能。当使用静态工厂方法创建对象时,缓存池允许在创建范围内的对象时重用现有对象,而不是每次都创建新对象。
Byte
、Short
、Integer
、Long
类缓存池的范围是-128 ~ 127
,Character
类缓存池的范围是0 ~ 127
。
Integer
类的缓存池(唯一能更改上界)实现如下:
ValueOf.java
java
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
tip提示
能创建“新”对象的静态方法被称为静态工厂方法。Integer.valueOf()
就是静态工厂方法,它尽可能地返回缓存的实例以节省内存。 创建新对象时,优先选用静态工厂方法而不是 new 操作符。
IntegerCache.java
java
private static final class IntegerCache {
static final int low = -128;
static final int high;
@Stable
static final Integer[] cache;
static Integer[] archivedCache;
static {
// high value may be configured by property
int h = 127;
String integerCacheHighPropValue =
VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
try {
h = Math.max(parseInt(integerCacheHighPropValue), 127);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(h, Integer.MAX_VALUE - (-low) -1);
} catch( NumberFormatException nfe) {
// If the property cannot be parsed into an int, ignore it.
}
}
high = h;
// Load IntegerCache.archivedCache from archive, if possible
CDS.initializeFromArchive(IntegerCache.class);
int size = (high - low) + 1;
// Use the archived cache if it exists and is large enough
if (archivedCache == null || size > archivedCache.length) {
Integer[] c = new Integer[size];
int j = low;
for(int i = 0; i < c.length; i++) {
c[i] = new Integer(j++);
}
archivedCache = c;
}
cache = archivedCache;
// range [-128, 127] must be interned (JLS7 5.1.7)
assert IntegerCache.high >= 127;
}
private IntegerCache() {}
}
自动装箱与自动拆箱
Auto-boxing and Auto-unboxing
装箱其实就是调用了包装类的valueOf()
方法,拆箱其实就是调用了xxxValue()
方法。
tip提示
- 自动装箱: 将基本数据类型自动转换为包装类型。例如:
Integer i = 10;
,等同于Integer i = Integer.valueOf(10);
。 - 自动拆箱: 将包装类型自动转换为基本数据类型。例如:
int i = new Integer(10);
,等同于int i = new Integer(10).intValue();
。