【Java学习笔记】35:泛型类和泛型方法

时间:2023-02-25 19:05:02

泛型使程序代码与类型无关,从而实现程序代码的重用,如前面学的集合都有一个抽象的类型参数,在使用时可以被指定为任何数据类型。

[1]泛型类

package day35;

//一个类型参数的泛型类
class AnyType<T>{
private T obj;

public AnyType(T obj) {
this.obj = obj;
}

public T getObj() {
return obj;
}

public void setObj(T obj) {
this.obj = obj;
}

//show the type of T
public void showType(){
System.out.println(this.obj+":"+this.obj.getClass().getName());
}
}

public class Test {

public static void main(String[] args) {
AnyType<String> at=new AnyType<String>("Hello");
at.showType();

AnyType<Integer> at2=new AnyType<Integer>(100);
at2.showType();

Person p=new Person("lzh");
AnyType<Person> at3=new AnyType<Person>(p);
at3.showType();
}

}

class Person{
private String name;

public Person(String name) {
this.name = name;
}

@Override
public String toString() {
return name;
}

}

运行结果:
Hello:java.lang.String
100:java.lang.Integer
lzh:day35.Person

package day35;
//多类型参数的泛型类
class Pair<T1,T2>{
private T1 first;
private T2 second;

@Override
public String toString() {
return first+":"+second;
}

public Pair(T1 first, T2 second) {
this.first = first;
this.second = second;
}

public T1 getFirst() {
return first;
}
public void setFirst(T1 first) {
this.first = first;
}
public T2 getSecond() {
return second;
}
public void setSecond(T2 second) {
this.second = second;
}

}

public class Test {

public static void main(String[] args) {
Pair<String,String> p1=new Pair<String,String>("8/29","lzh");
System.out.println(p1);
}
}

运行结果:
8/29:lzh

[2]泛型方法
除了定义泛型类之外,Java中在普通的类里还可以定义泛型方法。
泛型方法的抽象类型参数是介于返回值和修饰符之间的。

package day35;
//储存了三个静态的泛型方法的普通类
class Myclass{
public static <T> T FunMid(T[] a){
return a[a.length/2];
}

public static <T> T FunFst(T[] a){
return a[0];
}

public static <T> T FunLst(T[] a){
return a[a.length-1];
}

}
public class Test {

public static void main(String[] args) {
String[] a={"Tomcat","Hadoop","Flask","Flora","Django"};
System.out.print(Myclass.<String>FunFst(a)+" ");
System.out.print(Myclass.FunMid(a)+" ");//具体类型常可以省略
System.out.println(Myclass.FunLst(a));

Integer[] b={1,2,3,4,5,6};
System.out.print(Myclass.<Integer>FunFst(b)+" ");
System.out.print(Myclass.FunMid(b)+" ");//具体类型常可以省略
System.out.println(Myclass.FunLst(b));

Person[] c={new Person("lzh",2),new Person("SB",2),new Person("Other",1)};
System.out.print(Myclass.<Person>FunFst(c)+" ");
System.out.print(Myclass.FunMid(c)+" ");//具体类型常可以省略
System.out.println(Myclass.FunLst(c));

}
}

class Person{
String name;
int id;

public Person(String name, int id) {
this.name = name;
this.id = id;
}

@Override
public String toString() {
return id+":"+name;
}
}

运行结果:
Tomcat Flask Django
1 4 6
2:lzh 2:SB 1:Other