包装类把 8 种基本类型「包」成对象。基本类型不是对象,有些场景(比如泛型、集合)必须用对象,这时就需要包装类。

1. 8 种包装类

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

2. 自动装箱和拆箱

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class BoxingDemo {
public static void main(String[] args) {
// 自动装箱:基本类型 → 包装类
Integer i = 10;

// 自动拆箱:包装类 → 基本类型
int j = i;

System.out.println(i); // 10
System.out.println(j); // 10

// 参与运算时也会自动拆箱
Integer a = 5;
Integer b = 10;
int sum = a + b; // 自动拆箱再相加
System.out.println(sum); // 15
}
}

3. 字符串和数值互转

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class ParseDemo {
public static void main(String[] args) {
// 字符串 → 数字
int i = Integer.parseInt("123");
double d = Double.parseDouble("3.14");
System.out.println(i); // 123
System.out.println(d); // 3.14

// 数字 → 字符串
String s1 = String.valueOf(123);
String s2 = Integer.toString(456);
System.out.println(s1); // 123
System.out.println(s2); // 456
}
}

4. 一个重要的坑:Integer 缓存

Integer 对 -128 到 127 之间的值做了缓存。所以这个范围里的 == 比较是 true,范围外是 false。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class IntegerCacheDemo {
public static void main(String[] args) {
Integer a = 127;
Integer b = 127;
System.out.println(a == b); // true(命中缓存,是同一个对象)

Integer c = 128;
Integer d = 128;
System.out.println(c == d); // false(超出缓存,是两个不同对象)

// 正确做法:比较 Integer 用 equals
System.out.println(c.equals(d)); // true
}
}

结论:比较包装类对象用 equals,不要用 ==。

5. 常用方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class IntegerMethodDemo {
public static void main(String[] args) {
Integer i = 100;

// 转成各种基本类型
System.out.println(i.intValue()); // 100
System.out.println(i.doubleValue()); // 100.0

// 比较大小
System.out.println(Integer.compare(5, 10)); // -1(5 小于 10)
System.out.println(Integer.max(5, 10)); // 10
System.out.println(Integer.min(5, 10)); // 5

// 常量
System.out.println(Integer.MAX_VALUE); // 2147483647
System.out.println(Integer.MIN_VALUE); // -2147483648
}
}

小结

  • 包装类把基本类型变成对象,自动装箱/拆箱让两者可以混用
  • 字符串转数字用 Integer.parseInt 等,数字转字符串用 String.valueOf
  • 比较包装类对象用 equals(注意 Integer 的 -128~127 缓存陷阱)