包装类把 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); System.out.println(j);
Integer a = 5; Integer b = 10; int sum = a + b; System.out.println(sum); } }
|
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); System.out.println(d);
String s1 = String.valueOf(123); String s2 = Integer.toString(456); System.out.println(s1); System.out.println(s2); } }
|
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);
Integer c = 128; Integer d = 128; System.out.println(c == d);
System.out.println(c.equals(d)); } }
|
结论:比较包装类对象用 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()); System.out.println(i.doubleValue());
System.out.println(Integer.compare(5, 10)); System.out.println(Integer.max(5, 10)); System.out.println(Integer.min(5, 10));
System.out.println(Integer.MAX_VALUE); System.out.println(Integer.MIN_VALUE); } }
|
小结
- 包装类把基本类型变成对象,自动装箱/拆箱让两者可以混用
- 字符串转数字用
Integer.parseInt 等,数字转字符串用 String.valueOf
- 比较包装类对象用
equals(注意 Integer 的 -128~127 缓存陷阱)