Java 泛型是一种在编译时期强制进行类型检查的机制,它允许程序员在类、接口和方法中使用类型参数(type parameters)。泛型的主要好处是在编译时提供更强的类型检查,并且可以创建复用性更好的代码。
以下是 Java 泛型的一些基本应用实践:
泛型类
创建一个泛型类 Box,用于存储任意类型的数据。
1public class Box<T> {
2 private T t; // T 代表任意类型
3
4 public void set(T t) {
5 this.t = t;
6 }
7
8 public T get() {
9 return t;
10 }
11}
使用泛型类:
1public class GenericTest {
2 public static void main(String[] args) {
3 Box<Integer> integerBox = new Box<>();
4 Box<String> stringBox = new Box<>();
5
6 integerBox.set(10);
7 stringBox.set("Hello World");
8
9 System.out.println("Integer Value: " + integerBox.get());
10 System.out.println("String Value: " + stringBox.get());
11 }
12}
泛型方法
创建一个泛型方法,用于交换数组中的两个元素。
1public class ArrayUtil {
2 // 泛型方法
3 public static <T> void swap(T[] a, int i, int j) {
4 T temp = a[i];
5 a[i] = a[j];
6 a[j] = temp;
7 }
8}
使用泛型方法:
1public class GenericMethodTest {
2 public static void main(String[] args) {
3 Integer[] intArray = {1, 2, 3, 4, 5};
4 String[] stringArray = {"one", "two", "three", "four", "five"};
5
6 ArrayUtil.swap(intArray, 0, 4);
7 ArrayUtil.swap(stringArray, 1, 3);
8
9 System.out.println(Arrays.toString(intArray));
10 System.out.println(Arrays.toString(stringArray));
11 }
12}
泛型接口
定义一个泛型接口 Pair,表示一个包含两个元素的对。
1public interface Pair<K, V> {
2 public K getKey();
3 public V getValue();
4}
实现泛型接口:
1public class OrderedPair<K, V> implements Pair<K, V> {
2 private K key;
3 private V value;
4
5 public OrderedPair(K key, V value) {
6 this.key = key;
7 this.value = value;
8 }
9
10 @Override
11 public K getKey() {
12 return key;
13 }
14
15 @Override
16 public V getValue() {
17 return value;
18 }
19}
使用泛型接口:
1public class GenericInterfaceTest {
2 public static void main(String[] args) {
3 Pair<Integer, String> pair = new OrderedPair<>(1, "Apple");
4 System.out.println("Key: " + pair.getKey());
5 System.out.println("Value: " + pair.getValue());
6 }
7}
使用通配符
通配符 ? 使得泛型更加灵活,它代表未知的类型。
1public static void printBoxContent(Box<?> box) {
2 Object obj = box.get(); // 通配符类型为未知,因此只能赋值给 Object
3 System.out.println("Box contains: " + obj);
4}
使用通配符:
1public class WildcardTest {
2 public static void main(String[] args) {
3 Box<Integer> intBox = new Box<>();
4 intBox.set(10);
5 printBoxContent(intBox);
6
7 Box<String> stringBox = new Box<>();
8 stringBox.set("Hello World");
9 printBoxContent(stringBox);
10 }
11}
这些是 Java 泛型的一些基本应用实践。泛型在 Java 集合框架中广泛使用,如 List<E>, Map<K,V>, Set<E> 等,有助于提高代码的可读性和安全性。在设计自己的数据结构和算法时,合理使用泛型可以让代码更加通用和灵活。