类型转换错误在编译时不提醒,在运行时才会报错,是一个安全隐患
限制列表中的对象的种类
Listlist = new ArrayList<>();
注:变量声明的类型必须匹配传递给实际对象的类型
//错误案例, 继承父类的子类也不能使用不同的泛型 List泛型作为方法参数
//所有继承自父类Goods的泛型都可以穿入作为参数
public void sellGoods(List extends Goods> goods){
for(Goods g:goods){
g.sell();
}
}
泛型类
public class NumGeneric{ private T Num; public T getNum() { return Num; } public void setNum(T num) { Num = num; } //泛型类可以根据实例化时输入的不同泛型返回不同的结果 public static void main(String[] args) { NumGeneric num1 = new NumGeneric<>(); num1.setNum(80); System.out.println(num1.getNum()); NumGeneric num2 = new NumGeneric<>(); num2.setNum(3.5f); System.out.println(num2.getNum()); } }
输出结果
泛型方法不一定写在泛型类中。
public class MethGeneric {
public void printVal(T t) {
System.out.println(t);
}
public static void main(String[] args) {
MethGeneric mge = new MethGeneric();
mge.printVal(0.5);
}
}
输出结果



