什么是Java泛型?
泛型(Generics),指在定义类时,不指定类中信息的具体数据类型,暂时用一个标识符替代,当外部实例化对象的时候再来指定具体的数据类型。
用法: 泛型可以指代类中的成员变量的数据类型,方法的返回值类型,以及方法的参数类型。
优点: 这样做极大的提升程序的灵活性,提升类的扩展性。
//定义A时不指定属性的类型
public class A<T,E>{
private T b;
public E test(){
return E;
}
}
A<B,F> a = new A();//此时T变成B,b的类型为B,方法返回值类型为F
A<C,G> a = new A();//此时T变成C,b的类型为C,返回值为G
下面用一个实例,来解释
public class GenericsTest{
public static void main(String[] args) {
TimeGenerics<String,Integer,Float> timeGenerics = new TimeGenerics<>();
timeGenerics.setHour("十点");
timeGenerics.setMinute(25);
timeGenerics.setSecond(10f);
System.out.println(timeGenerics.getHour()+timeGenerics.getMinute()+"分"+timeGenerics.getSecond