1编写泛型
- 编写泛型类比普通类要复杂
- 泛型类一般用在集合类中 ArrayList<T>
- 很少需要编写泛型类
如何编写一个泛型类:
- 按照某种类型(例如String)编写类
- 标记所有的特定类型(例如String)
- 把特定类型替换为T,并申明<T>
public class Pair<T> {
private T first;
private T last;
public Pair(T first,T last) {
this.first = first;
this.last = last;
}
public T getFirst() {
return first;
}
public T getLast() {
return last;
}
}
2代码演示
public class Main {
public static void main(String[] args) {
Pair<String> p = new Pair<String>("Xiao", "Ming");
String first = p.getFirst();
String last = p.getLast();
System.out.println(first);
System.out.println(last);
System.out.println(p.getClass() == Pair.class);
}
}
public class Pair<T> {
private T first;
private T last;
public Pair(T first,T last) {
this.first = first;
this.last = last;
}
public T getFirst() {
return first;
}
public void setFirst(T first) {
this.first = first;
}
public T getLast() {
return last;
}
public void setLast(T last) {
this.last = last;
}
public String toString() {
return "Pair(" + first + ", " + last + ")";
}
}
3泛型类型<T>不能用于静态方法
- 编译错误
- 编译器无法在静态字段或静态方法中使用泛型类型<T>
静态方法可以单独改写为“泛型”方法:
- 使用另一个类型<K>
public class Pair<T> {
private T first;
private T last;
public Pair(T first,T last) {
this.first = first;
this.last = last;
}
public T getFirst() {...}
public T getLast() {...}
//错误代码
public static Pair<T> create(T first,T last) {
return new Pair<T>(first,last);
}
//改写为另一个类型<K>则可以通过
public static<K> Pair<K> create(K first,K last) {
return new Pair<K>(first,last);
}
}
4泛型可以定义多种类型
泛型可以定义多种类型:
- 使用类型<T,K>
public class Pair<T,K> {
private T first;
private K last;
public Pair(T first,K last) {
this.first = first;
this.last = last;
}
public T getFirst() {...}
public K getLast() {...}
}
Pair<String,Integer> p = new Pair<>("test",123);
对上述代码进行改变:
public class Main {
public static void main(String[] args) {
//Pair<String> p = new Pair<String>("Xiao", "Ming");
Pair<Integer> p = Pair.create(1, 2);
Integer first = p.getFirst();
Integer last = p.getLast();
System.out.println(first);
System.out.println(last);
System.out.println(p.getClass() == Pair.class);
}
}
public class Pair<T> {
private T first;
private T last;
public Pair(T first,T last) {
this.first = first;
this.last = last;
}
public T getFirst() {
return first;
}
public void setFirst(T first) {
this.first = first;
}
public T getLast() {
return last;
}
public void setLast(T last) {
this.last = last;
}
public String toString() {
return "Pair(" + first + ", " + last + ")";
}
static<K> Pair<K> create(K first,K last){
return new Pair<K>(first, last);
}
}
5总结
- 编写泛型时,需要定义泛型类型<T> public class Pair<T>{...}
- 静态方法不能引用泛型类型<T>,必须定义其他类型<K>来实现“泛型” public static<K> Pair<K> create(K first,K last){...}
- 泛型可以同时定义多种类型<T,K> public class Pair<T,K>{...}