Java 泛型(Generics)
在Java泛型中,
T 是一个
类型参数(Type Parameter)的占位符,通常用于表示任意类型(可以是类、接口、数组等)。
基础泛型类(Generic Class)
public class Main {
public static void main(String[] args) {
Box<String> stringBox = new Box<>();
stringBox.setContent("Hello Generics");
System.out.println(stringBox.getContent()); // 输出: Hello Generics
Box<Integer> intBox = new Box<>();
intBox.setContent(123);
System.out.println(intBox.getContent()); // 输出: 123
}
}
class Box<T> {
private T content;
public void setContent(T content) {
this.content = content;
}
public T getContent() {
return content;
}
}
泛型方法(Generic Method)
public class Main {
public static void main(String[] args) {
String[] words = {"A", "B", "C"};
Utils.swap(words, 0, 2); // 交换第0和第2个元素
System.out.println(Arrays.toString(words)); // 输出: [C, B, A]
}
}
class Utils {
// 泛型方法:交换数组中的两个元素
public static <T> void swap(T[] array, int i, int j) {
T temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
泛型接口(Generic Interface)
public class Main {
public static void main(String[] args) {
Pair<String, Integer> pair = new OrderedPair<>("Age", 25);
System.out.println(pair.getKey() + ": " + pair.getValue()); // 输出: Age: 25
}
}
// 泛型接口:表示一个键值对
interface Pair<K, V> {
K getKey();
V getValue();
}
// 实现泛型接口
class OrderedPair<K, V> implements Pair<K, V> {
private K key;
private V value;
public OrderedPair(K key, V value) {
this.key = key;
this.value = value;
}
@Override
public K getKey() { return key; }
@Override
public V getValue() { return value; }
}
类型通配符(Wildcards)
public class Main {
public static void main(String[] args) {
List<String> strings = Arrays.asList("A", "B", "C");
List<Integer> numbers = Arrays.asList(1, 2, 3);
Printer.printList(strings); // 输出: A B C
Printer.printList(numbers); // 输出: 1 2 3
}
}
class Printer {
// 打印任何类型的List(使用通配符?)
public static void printList(List<?> list) {
for (Object item : list) {
System.out.print(item + " ");
}
System.out.println();
}
}
泛型与继承(extends/super)
public class Main {
public static void main(String[] args) {
List<Dog> dogs = new ArrayList<>();
dogs.add(new Dog());
List<Object> objects = new ArrayList<>();
Zoo.addAnimals(dogs); // 输出: Added: Dog
Zoo.addToAnimalList(objects); // 可以向List<Object>安全添加Animal及其子类(如Dog、Cat)
}
}
class Animal {}
class Dog extends Animal {}
class Cat extends Animal {}
class Zoo {
// 只接受Animal及其子类的List(上界通配符)
public static void addAnimals(List<? extends Animal> animals) {
for (Animal animal : animals) {
System.out.println("Added: " + animal.getClass().getSimpleName());
}
}
// 只接受Animal及其父类的List(下界通配符)
public static void addToAnimalList(List<? super Animal> list) {
list.add(new Dog());
list.add(new Cat());
}
}
1061

被折叠的 条评论
为什么被折叠?



