Java 5 (代號 Tiger) 引入革命性語言特性,徹底改變 Java 開發體驗。本文透過完整可執行範例,帶您快速掌握四大核心新特性:泛型、列舉、可變長度參數、格式化輸出。
class GenericBox<T> {
private T value;
public void set(T value) { this.value = value; }
public T get() { return value; }
}
// 使用
GenericBox<String> boxStr = new GenericBox<>();
boxStr.set("Hello");
String s = boxStr.get(); // 編譯期類型檢查,無需強制轉型
ClassCastException 風險
// 型別參數限定為 Exception 子類
interface Action<E extends Exception> {
void execute() throws E;
}
class ActionRunner {
public static <E extends Exception> void run(Action<E> action) throws E {
action.execute();
}
}
// 使用:匿名類別實作不同例外類型
ActionRunner.run(new Action<IOException>() {
public void execute() throws IOException { /* ... */ }
});
// 三種等效寫法
StringBuilder sb = new StringBuilder();
new Formatter(sb).format("PI = %12.10f%n", Math.PI);
System.out.print(sb);
System.out.printf("PI = %12.10f%n", Math.PI);
String formatted = String.format("PI = %12.10f", Math.PI);
| 符號 | 說明 | 範例輸出 |
|---|---|---|
%d | 整數 | 42 |
%f | 浮點數 | 3.141593 |
%.2f | 保留 2 位小數 | 3.14 |
%s | 字串 | Hello |
%n | 平台相關換行 | - |
%,d | 千分位分隔 | 1,000,000 |
public static void printFriends(String... names) {
for (String name : names) {
System.out.print(name + " ");
}
System.out.println();
}
// 呼叫方式多樣
printFriends("Alice", "Bob", "Carol"); // 多個參數
printFriends(new String[]{"Dave", "Eve"}); // 陣列
printFriends(); // 零參數
foo(int...) vs foo(int, int...)List<String> list = Arrays.asList("A", "B", "C");
for (String s : list) { System.out.println(s); }
// 等同於迭代器模式,但語法更簡潔
// 適用於實作 Iterable 的所有集合與陣列
enum Season { SPRING, SUMMER, AUTUMN, WINTER }
public class EnumDemo {
public static void main(String[] args) {
Season now = Season.AUTUMN;
System.out.println(now); // 輸出: AUTUMN
// 遍歷所有值
for (Season s : Season.values()) {
System.out.print(s + " ");
}
// switch 完美支援
switch (now) {
case SPRING: System.out.println("花開"); break;
case SUMMER: System.out.println("酷熱"); break;
case AUTUMN: System.out.println("豐收"); break;
case WINTER: System.out.println("寒冬"); break;
}
}
}
enum Size {
SMALL(0.8), MEDIUM(1.0), LARGE(1.2), XL(1.2);
private final double factor;
Size(double factor) { this.factor = factor; }
public double getFactor() { return factor; }
// 常數特定類別主體:個別覆寫方法
EXTRA_LARGE(1.5) {
@Override public String toString() { return "XL (Special)"; }
};
}
// 使用
System.out.println(Size.LARGE.getFactor()); // 1.2
System.out.println(Size.EXTRA_LARGE); // XL (Special)
// EnumMap: 鍵為列舉,極致效能
Map<Size, String> desc = new EnumMap<>(Size.class);
desc.put(Size.SMALL, "S");
desc.put(Size.LARGE, "L");
// EnumSet: 列舉集合,位元向量實現,極快
EnumSet<Size> all = EnumSet.allOf(Size.class);
EnumSet<Size> smallMedium = EnumSet.range(Size.SMALL, Size.MEDIUM);
EnumSet<Size> nonStandard = EnumSet.complementOf(EnumSet.of(Size.SMALL, Size.MEDIUM, Size.LARGE));
# 編譯
javac -d out src/tigers/*.java
# 執行 (注意未檢查警告為正常,泛型擦除導致)
java -cp out tigers.GenericIdentify
Java 5 的四大特性相輔相成:
int 常數,提供類型安全、命名空間、豐富行為配合增強 for 迴圈、靜態導入、自動裝箱/拆箱、Annotation 等特性,Java 5 讓開發者能寫出更安全、更簡潔、更具表達力的代碼。建議在真實專案中逐步遷移採用,體驗現代 Java 開發樂趣。