一、什么是泛型?
泛型是一种特殊的类型。可以代表多种类型。是一种模板,编写一套代码,可以适应多种类型。
二、泛型类
public class Hi {
public static void main(String[] args) throws Exception {
Pair pair1 = new Pair("first", "last");
PairG<Integer> pairG1 = new PairG<Integer>(1, 2);
PairG<String> pairG2 = new PairG<String>("first", "last");
System.out.println(pair1.getFirst());
System.out.println(pairG1.getFirst());
System.out.println(pairG2.getFirst());
}
}
class Pair{
private String first;
private String last;
public Pair(String first,String last) {
this.first = first;
this.last = last;
}
public String getFirst() {
return first;
}
public String getLast() {
return last;
}
}
class PairG<T>{
private T first;
private T last;
public PairG(T first,T last) {
this.first = first;
this.last = last;
}
public T getFirst() {
return first;
}
public T getLast() {
return last;
}
}
三、泛型方法
public class Hi {
public static void main(String[] args) throws Exception {
int[] a = {1,2,3};
printArray(a);
String[] s = {"a","b","c"};
printArrayG(s);
}
public static void printArray(int[] a){
for (var item : a) {
System.out.println(item);
}
}
public static <T> void printArrayG(T[] a){
for (var item : a) {
System.out.println(item);
}
}
}