// 泛型类
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Comparator;
class Node<T> {
public T value;
public Node(T value) {
this.value = value;
}
public void print(T value) {
System.out.println(value);
}
}
public class Test {
public static void main(String[] args) {
// 使用泛型类创建对象,new后面可以省略泛型类型
Node<Integer> node = new Node<>(1);
// 使用通配符?,表示任意类型
Node<?> node2 = new Node<Integer>(1);
node2 = new Node<>("hello");
// 方法调用(和泛型类同一类型)
node.print(node.value);
print("hello world");
print(123);
Integer[] arr = { 1, 3, 2, 5, 4 };
Arrays.sort(arr, new Comparator<Integer>() {
@Override
public int compare(Integer a, Integer b) {
return a - b;
}
});
for (Integer i : arr) {
System.out.println(i);
}
}
// 泛型方法
public static <T> void print(T value) {
System.out.println(value);
}
}
// 泛型与多态
interface Study<T> {
T test();
}
class MathStudy implements Study<Integer> {
// 在实现接口或是继承父类时,如果子类是一个普通类,那么可以直接明确对应类型
@Override
public Integer test() {
return 123;
}
}
// 继续实现为泛型类
class LanguageStudy<T> implements Study<T> {
@Override
public T test() {
return null;
}
}
// 继承也是一样
class ChineseStudy extends LanguageStudy<String> {
@Override
public String test() {
return "Chinese";
}
}
// 泛型的界限
class 动物 {
}
class 植物 {
}
class 犬科 extends 动物 {
}
class 猫科 extends 动物 {
}
class 狗 extends 犬科 {
}
class 猫 extends 猫科 {
}
// 泛型的界限,表示T必须是动物类及其子类
public class 养宠物<T extends 动物> {
public static void main(String[] args) {
// 养宠物<植物> p1 = new 养宠物<植物>(); // 不可以,只能养动物
// 养宠物<? extends 犬科> p3 = new 养宠物<动物>(); // 不可以,只能养犬科类动物
养宠物<? extends 犬科> p4 = new 养宠物<狗>(); // 可以
// 养宠物<? super 狗> p5 = new 养宠物<猫>(); // 不可以,只能养狗类及其父类
}
}