编写泛型
373字约1分钟
2024-08-08
如何编写泛型
第一步,编写类
public class Animal {
private String name;
private String type;
public Animal(String name, String type) {
this.name = name;
this.type = type;
}
public String getName() {
return name;
}
public String getType() {
return type;
}
}
第二步,把特定类型 String
替换为 T
,并声明 <T>
public class Animal<T> {
private T name;
private T type;
public Animal(T name, T type) {
this.name = name;
this.type = type;
}
public T getName() {
return name;
}
public T getType() {
return type;
}
}
熟练之后可以直接写第二步
静态方法
编写泛型类时,泛型类型 <T>
不能用于静态方法,下述代码会导致编译错误
public class Animal<T> {
private T name;
private T type;
public Animal(T name, T type) {
this.name = name;
this.type = type;
}
......
public static <T> Animal<T> run(T name, T type) {
return new Animal<T>(name, type);
}
}
我们在 static
修饰符后面加一个 <T>
,编译就能通过
public class Animal<T> {
private T name;
private T type;
public Animal(T name, T type) {
this.name = name;
this.type = type;
}
......
public static <T> Animal<T> run(T name, T type) {
return new Animal<T>(name, type);
}
}
实际上,这里的 T
和 Animal<T>
类型的 <T>
没有任何关系,所以我们把静态方法改成另一种泛型类型,比如 <K>
public class Animal<T> {
private T name;
private T type;
public Animal(T name, T type) {
this.name = name;
this.type = type;
}
......
public static <K> Animal<K> run(K name, K type) {
return new Animal<K>(name, type);
}
}
多个泛型类型
泛型还可以定义多种类型
public class Animal<T, K> {
private T name;
private K type;
public Animal(T name, K type) {
this.name = name;
this.type = type;
}
public T getName() {
return name;
}
public K getType() {
return type;
}
}