java的各种语法都是提高开发效率。
当你设计一个盘子类(Plate) 用来放一种 水果时。水果有 苹果(Apple) 橘子(Orange) 等。
class Apple{...}
class Orange{...}
class PlateA{
public Apple apple;
public PlateA(Apple apple){
this.apple = apple;
}
}
class PlateB{
public Orange orange;
public PlateB(Orange orange){
this.orange = orange;
}
}
PlateA a = new PlateA(new Apple());
PlateB b = new PlateB(new Orange());
你会发现这个两个Plate类 有好多相似的 如果水果越多 这样写就很麻烦。有没有方便写法? 有 ,那就是泛型写法。
Class Plate<T> {
public T fruit;
public Plate(T fruit){
this.fruit = fruit;
}
}
Plate<Apple> a = new Plate<Apple>(new Apple());
Plate<Orange> b = new Plate<Orange>(new Orange());
?是通配符,泛指所有类型
以为代码还可以简写
Plate<?> a = new Plate<Apple>(new Apple());
Plate<?> b = new Plate<Orange>(new Orange());
泛型,即“可变的类名”。其中T 就是一个类名 这个类名 可以是Apple 也可以是Orange。
一提到参数,最熟悉的就是定义方法时有形参,然后调用此方法时传递实参。那么参数化类型怎么理解呢?
顾名思义,就是将类型由原来的具体的类型参数化,类似于方法中的变量参数,此时类型也定义成参数形式(可以称之为类型形参),
然后在使用/调用时传入具体的类型(类型实参)。
泛型的本质是为了参数化类型(在不创建新的类型的情况下,通过泛型指定的不同类型来控制形参具体限制的类型)。也就是说在泛型使用过程中,
操作的数据类型被指定为一个参数,这种参数类型可以用在类、接口和方法中,分别被称为泛型类、泛型接口、泛型方法。