Java 基本類型(byte, short, int, long, float, double, char, boolean)非對象,無法直接用於集合、泛型、反射等 OO 場景。包裝類將其「對象化」,位於 java.lang:
| 基本類型 | 包裝類 |
|---|---|
| byte | Byte |
| short | Short |
| int | Integer |
| long | Long |
| float | Float |
| double | Double |
| char | Character |
| boolean | Boolean |
以 Integer 為例,其他類似。
// 裝箱:基本 → 包裝
Integer i1 = 100; // 自動調用 Integer.valueOf(100)
Integer i2 = Integer.valueOf(100); // 手動
// 拆箱:包裝 → 基本
int n = i1; // 自動調用 i1.intValue()
int m = i2.intValue(); // 手動
// String → int
int a = Integer.parseInt("123"); // 十進制
int b = Integer.parseInt("FF", 16); // 十六進制 → 255
int c = Integer.parseInt("1111", 2); // 二進制 → 15
// int → String
String s1 = Integer.toString(123); // "123"
String s2 = Integer.toString(255, 16); // "ff" 十六進制
String s3 = Integer.toBinaryString(15); // "1111" 二進制
String s4 = String.valueOf(123); // 通用靜態方法
Integer.MAX_VALUE // 2^31-1 = 2147483647
Integer.MIN_VALUE // -2^31 = -2147483648
Integer.SIZE // 32 位
Integer.BYTES // 4 字節 (JDK 8+)
Integer.valueOf(int) 內部緩存 [-128, 127] 範圍對象,new Integer() 每次新建。自動裝箱調用 valueOf。
Integer a = 100, b = 100;
System.out.println(a == b); // true (緩存命中)
Integer c = 200, d = 200;
System.out.println(c == d); // false (超出緩存,新建對象)
Integer e = new Integer(100);
Integer f = new Integer(100);
System.out.println(e == f); // false (new 繞過緩存)
結論:包裝類比較值必須用 equals(),絕不使用 ==。
Integer obj = null;
int val = obj; // 拆箱時拋 NullPointerException
集合存儲、數據庫查詢可能返回 null,拆箱前必須判空。
// 低效:每次 += 觸發拆箱+裝箱,創建大量 Integer 對象
Integer sum = 0;
for (int i = 0; i < 100000; i++) sum += i;
// 高效:用基本類型累加,最後裝箱
int sum = 0;
for (int i = 0; i < 100000; i++) sum += i;
Integer result = sum;
| 類 | 特有方法/特性 |
|---|---|
| Character | isDigit, isLetter, isUpperCase, toUpperCase, getNumericValue |
| Boolean | TRUE, FALSE 兩單例,valueOf(String) 忽略大小寫解析 |
| Byte/Short | 少用,注意自動提升為 int 運算 |
| Float/Double | isNaN, isInfinite, compareTo(處理 NaN 排序),floatToIntBits |
equals(),== 僅比較引用。Objects.requireNonNull/Optional。valueOf 優於 new;JDK 9+ Integer.valueOf 緩存範圍可配置 (-XX:AutoBoxCacheMax)。