泛型
文章目录
泛型
限制类型参数
限制类型参数 — 接收泛型数组返元素最大值方法限制类型参数 — 要求传入的类型必须可比较
限制类型参数
可以通过 extends 对类型参数增加一些限制条件,比如
extends 后面可以跟上类名、接口名,代表 T 必须是 A 类型,或者继承、实现 A
// 表示传入的类型参数必须是Numbe及其子类
public class Person {
private T age;
public Person(T age) {
this.age = age;
}
public int getAge() {
// 传入null则视为0, 否则转为int
return (age == null) ? 0 : age.intValue();
}
}
public static void main(String[] args) {
Person p1 = new Person<>(18.7);
System.out.println(p1.getAge()); // 18
Person p2; // 正常运行, Integer是Number的子类
// Person p3; // 会报错, 因为String不是Number的子类
}
可以同时添加多个限制,比如 ,代表 T 必须同时满足 A、B、C,只能有一个类,但是可以有多个接口,类必须放在前面
限制类型参数 — 接收泛型数组返元素最大值方法
public class Main {
public static void main(String[] args) {
Double[] ds = {5.6, 3.4, 8.8, 4.6};
System.out.println(getMax(ds)); // 8.8
Integer[] is = {4, 19, 3, 28, 56};
System.out.println(getMax(is)); // 56
}
static > T getMax(T[] array) {
if (array == null || array.length == 0) return null;
T max = array[0];
for (int i = 0; i < array.length; i++) {
if (array[i] == null) continue;
if (array[i].compareTo(max) <= 0) continue;
max = array[i];
}
return max;
}
}
限制类型参数 — 要求传入的类型必须可比较
public class Student > implements Comparable> {
private T score; // 传入的 T 继承了 Comparable, 表示是可比较的
public Student(T score) {
this.score = score;
}
@Override
public int compareTo(Student s) {
// 传入若为null, 必然比本身小
if (s == null) return 1;
// 若自身的score不为null, 则调用compareTo与传入的进行比较
if (score != null) return score.compareTo(s.score);
// 此时, 自身的score为null, 若传入的score也为null则视为相同, 否则就是传入的大
return s.score == null ? 0 : -1;
}
@Override
public String toString() {
return "Student [score=" + score + "]";
}
}
public class Main {
public static void main(String[] args) {
Student[] stus = new Student[3];
stus[0] = new Student<>(18);
stus[1] = new Student<>(38);
stus[2] = new Student<>(28);
// Student [score=38]
System.out.println(getMax(stus));
}
static > T getMax(T[] array) {
if (array == null || array.length == 0) return null;
T max = array[0];
for (int i = 0; i < array.length; i++) {
if (array[i] == null) continue;
if (array[i].compareTo(max) <= 0) continue;
max = array[i];
}
return max;
}
}