本文目录导读:

我来通过几个实际案例系统地讲解Java泛型方法的编写。
基础泛型方法
public class GenericMethodDemo {
// 基础泛型方法 - 打印任意类型的数组
public static <T> void printArray(T[] array) {
for (T element : array) {
System.out.print(element + " ");
}
System.out.println();
}
// 测试
public static void main(String[] args) {
Integer[] intArray = {1, 2, 3, 4, 5};
String[] strArray = {"Hello", "World", "Java"};
Double[] doubleArray = {1.1, 2.2, 3.3};
// 调用泛型方法
printArray(intArray);
printArray(strArray);
printArray(doubleArray);
}
}
返回泛型类型的方法
public class GenericReturnDemo {
// 返回第一个元素
public static <T> T getFirst(T[] array) {
if (array == null || array.length == 0) {
return null;
}
return array[0];
}
// 交换数组中的两个元素
public static <T> void swap(T[] array, int i, int j) {
T temp = array[i];
array[i] = array[j];
array[j] = temp;
}
public static void main(String[] args) {
Integer[] numbers = {1, 2, 3, 4, 5};
String[] names = {"Alice", "Bob", "Charlie"};
// 类型推断 - 不需要显式指定类型
Integer firstNum = getFirst(numbers);
String firstName = getFirst(names);
System.out.println("First number: " + firstNum);
System.out.println("First name: " + firstName);
// 交换方法测试
swap(names, 0, 2);
System.out.println("After swap - First: " + names[0]);
}
}
带边界(Bounded)的泛型方法
public class BoundedGenericDemo {
// 比较两个对象,返回较大的一个
public static <T extends Comparable<T>> T max(T x, T y) {
if (x.compareTo(y) > 0) {
return x;
}
return y;
}
// 计算数值类型的总和
public static <T extends Number> double sum(T num1, T num2) {
return num1.doubleValue() + num2.doubleValue();
}
public static void main(String[] args) {
// 测试 max 方法
System.out.println("Max of 3 and 7: " + max(3, 7));
System.out.println("Max of 'apple' and 'banana': " + max("apple", "banana"));
// 测试 sum 方法
System.out.println("Sum of 5 and 10: " + sum(5, 10));
System.out.println("Sum of 3.14 and 2.86: " + sum(3.14, 2.86));
}
}
多类型参数泛型方法
public class MultipleTypeParams {
// 键值对方法
public static <K, V> boolean compare(Pair<K, V> p1, Pair<K, V> p2) {
return p1.getKey().equals(p2.getKey()) &&
p1.getValue().equals(p2.getValue());
}
// 自定义Pair类
static class Pair<K, V> {
private K key;
private V value;
public Pair(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey() { return key; }
public V getValue() { return value; }
}
public static void main(String[] args) {
Pair<Integer, String> p1 = new Pair<>(1, "apple");
Pair<Integer, String> p2 = new Pair<>(2, "banana");
Pair<Integer, String> p3 = new Pair<>(1, "apple");
System.out.println("p1 equals p2: " + compare(p1, p2));
System.out.println("p1 equals p3: " + compare(p1, p3));
}
}
实用案例:集合工具类
import java.util.*;
public class CollectionUtils {
// 将数组转换为List
public static <T> List<T> arrayToList(T[] array) {
List<T> list = new ArrayList<>();
for (T element : array) {
list.add(element);
}
return list;
}
// 查找集合中的最大值
public static <T extends Comparable<T>> T findMax(Collection<T> collection) {
if (collection.isEmpty()) {
return null;
}
return Collections.max(collection);
}
// 过滤null值
public static <T> List<T> filterNull(List<T> list) {
List<T> result = new ArrayList<>();
for (T item : list) {
if (item != null) {
result.add(item);
}
}
return result;
}
// 合并两个集合(去重)
public static <T> Set<T> union(Collection<T> col1, Collection<T> col2) {
Set<T> result = new HashSet<>(col1);
result.addAll(col2);
return result;
}
public static void main(String[] args) {
// 测试 arrayToList
String[] strArray = {"Java", "Python", "C++"};
List<String> strList = arrayToList(strArray);
System.out.println("Array to List: " + strList);
// 测试 findMax
List<Integer> numbers = Arrays.asList(3, 8, 1, 9, 4);
Integer max = findMax(numbers);
System.out.println("Max number: " + max);
// 测试 filterNull
List<String> withNull = new ArrayList<>(Arrays.asList("a", null, "b", null, "c"));
List<String> withoutNull = filterNull(withNull);
System.out.println("Filtered list: " + withoutNull);
// 测试 union
Set<Integer> set1 = new HashSet<>(Arrays.asList(1, 2, 3, 4));
Set<Integer> set2 = new HashSet<>(Arrays.asList(3, 4, 5, 6));
Set<Integer> unionSet = union(set1, set2);
System.out.println("Union: " + unionSet);
}
}
泛型方法的最佳实践示例
public class BestPracticesDemo {
// 泛型方法中的类型推断
public static <T> T getValue(T value) {
return value;
}
// 使用通配符的泛型方法
public static void printList(List<?> list) {
for (Object elem : list) {
System.out.print(elem + " ");
}
System.out.println();
}
// 生产者和消费者原则 (PECS)
public static <T> void copy(List<? extends T> source, List<? super T> dest) {
for (T item : source) {
dest.add(item);
}
}
public static void main(String[] args) {
// 类型推断
Integer intVal = getValue(42);
String strVal = getValue("Hello");
System.out.println("Inferred types: " + intVal + ", " + strVal);
// 通配符使用
List<Integer> intList = Arrays.asList(1, 2, 3);
List<String> strList = Arrays.asList("A", "B", "C");
printList(intList);
printList(strList);
// PECS原则应用
List<Integer> ints = Arrays.asList(1, 2, 3);
List<Number> nums = new ArrayList<>();
copy(ints, nums);
System.out.println("Copied numbers: " + nums);
}
}
- 语法格式:
<T>放在返回类型之前 - 类型推断:Java能自动推断泛型类型
- 边界限定:使用
extends限制类型范围 - 多类型参数:可以定义
<K, V>等多种类型 - PECS原则:Producer extends, Consumer super
这些案例涵盖了Java泛型方法的主要使用场景,从基础到高级应用。