0%

Java包装类

前言:巩固基础,复习总结一下Java包装类

简介

Java提供了8种基本数据类型及对应的8种包装数据类型。如下表

基本数据类型 包装类型
byte Byte
boolean Boolean
short Short
char Character
int Integer
long Long
float Float
double Double

自动装箱和拆箱

1
2
3
4
5
6
7
8
9
10
11
Integer num1 = new Integer(128);

Integer num2 = Integer.valueOf(128);

// 自动装箱
Integer num3 = 128;

int num4 = num3.intValue();

// 自动拆箱
int num5 = num3;

关于Integer,对-128——127之间的数据会有缓存,类似String常量池,这需要注意

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// IntegerCache会存储-128——127之间的数据
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer cache[];

static {
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);
h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
} catch( NumberFormatException nfe) { 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++);

assert IntegerCache.high >= 127;
}

private IntegerCache() {}
}
-------------本文结束感谢您的阅读-------------