导入
泛型类(orientation)
学习如何使用泛型设计可重用、类型安全的类,使编译器能够在代码运行前检测到类型错误。
1class LegacyBox { 2 private Object value; 3 4 public void set(Object value) { 5 this.value = value; 6 } 7 8 public Object get() { 9 return value; 10 } 11} 12 13public class Main { 14 public static void main(String[] args) { 15 LegacyBox stringBox = new LegacyBox(); 16 stringBox.set("Hello World"); 17 18 // 我们必须强制转换为 (String),因为 get() 返回的是 Object 19 String text = (String) stringBox.get(); 20 System.out.println("Value: " + text); 21 22 // 危险:我们可能会不小心将 Integer 放入一个预期存放 String 的盒子中 23 LegacyBox numberBox = new LegacyBox(); 24 numberBox.set(100); 25 26 // 这段代码可以成功编译,但在运行时会因 ClassCastException 而崩溃 27 // 我们试图将 Integer 强制转换为 String 变量 28 String error = (String) numberBox.get(); 29 } 30}
1// T 是“类型”的占位符 2public class Box<T> { 3 // 我们使用 T 而不是 Object 4 private T value; 5 6 public void set(T value) { 7 this.value = value; 8 } 9 10 public T get() { 11 return value; 12 } 13}
1public class Main { 2 public static void main(String[] args) { 3 // T 变成 String 4 Box<String> stringBox = new Box<>(); 5 stringBox.set("Hello Generics"); 6 7 // 无需强制转换!get() 返回的是 String,而不是 Object 8 String message = stringBox.get(); 9 System.out.println(message); 10 11 // T 变成 Integer 12 Box<Integer> intBox = new Box<>(); 13 intBox.set(123); 14 System.out.println(intBox.get()); 15 16 // 编译错误! 17 // 编译器知道 intBox 只能持有 Integer。 18 // 它会阻止我们传入一个 String。 19 // intBox.set("Wrong Type"); 20 } 21}
1// 一个简单的容器,用于存放两个相关对象 2class Pair<K, V> { 3 private K key; 4 private V value; 5 6 public Pair(K key, V value) { 7 this.key = key; 8 this.value = value; 9 } 10 11 public K getKey() { return key; } 12 public V getValue() { return value; } 13} 14 15public class PairExample { 16 public static void main(String[] args) { 17 // K 是 Integer,V 是 String 18 Pair<Integer, String> result = new Pair<>(404, "Not Found"); 19 20 System.out.println("Code: " + result.getKey()); 21 System.out.println("Message: " + result.getValue()); 22 } 23}
1// 1. 定义泛型接口 2interface Repository<T> { 3 void save(T data); 4 T find(); 5} 6 7// 2. 方法 A:实现类保持泛型 8// 它将类中的 'T' 传递给接口 9class GenericRepository<T> implements Repository<T> { 10 private T data; 11 12 public void save(T data) { this.data = data; } 13 public T find() { return data; } 14} 15 16// 3. 方法 B:实现类锁定类型 17// 它用具体类型(例如 String)替换 'T' 18class StringRepository implements Repository<String> { 19 private String data; 20 21 public void save(String data) { this.data = data; } 22 public String find() { return data; } 23} 24 25public class GenericInterface { 26 public static void main(String[] args) { 27 // 使用泛型实现 28 Repository<Integer> numRepo = new GenericRepository<>(); 29 numRepo.save(42); 30 System.out.println("Generic found: " + numRepo.find()); 31 32 // 使用特定实现 33 Repository<String> strRepo = new StringRepository(); 34 strRepo.save("Fixed Type"); 35 System.out.println("String found: " + strRepo.find()); 36 } 37}