一、泛型是什么?
Java泛型是jdk 1.5中引入的一个新特性,其本质是参数化类型,也就是说所操作的数据类型被指定为一个参数(type parameter)这种参数类型可以用在类、接口和方法的创建中,分别称为泛型类、泛型接口、泛型方法。
在泛型中可以声明多个类型参数。为了指定两个或更多个类型参数,只需要使用逗号分隔参数列表即可。
二、泛型类
案例:
public static class Hello<T> {
private T t;
public Hello(T t) {
this.t = t;
}
public T getT() {
return t;
}
public void setT(T t) {
this.t = t;
}
//应用于方法的形参
public void fun1(){
System.out.println(this.t);
}
}
//测试类中,调用构造方法,传入不同的类型作为参数,创建对象。
public static void main(String[] args) {
Hello<Integer> hello=new Hello<Integer>(2020);
hello.fun1();
Hello<String> hello1=new Hello<String>("Hello World");
hello1.fun1();
}
编译以上代码,运行结果如下所示:
2020
Hello World
三、泛型方法
案例:
public static <T> void fun1(T t){
System.out.println(t);
}
public static void main(String[] args) {
String s=new String("HelloWorld");
fun1(s);
Integer i=new Integer(2020);
fun1(i);
}
编译以上代码,运行结果如下所示:
HelloWorld
2020
四、泛型接口
代码如下:
public interface Haha <T> {
void ff(T t);
}
五、泛型通配符
<? extent 类型> 表示某个类型或它的任意子类型
<? super 类型> 表示某个类型或它的任意父类型
案例:
Animal类
public abstract class Animal {
public abstract int num();
}
Dog类
public class Dog extends Animal {
@Override
public int num() {
return 4;
}
}
Penguin类
public class Penguin extends Animal {
@Override
public int num() {
return 2;
}
}
测试类
public class one {
public static void main(String[] args) {
//分别计算一批动物(2只狗狗和3只企鹅)的腿的数量。
List<Animal> list = new ArrayList();
list.add(new Dog());
list.add(new Dog());
list.add(new Penguin());
list.add(new Penguin());
list.add(new Penguin());
fun1(list);
}
private static void fun1(List<?extends Animal> t) {
int pp=0;
for (Animal o:t) {
pp+=o.num();
}
System.out.println(pp);
}
}
编译以上代码,运行结果如下所示:
14根腿