概述
为什么使用泛型
- 在Java增加泛型之前,泛型程序设计使用继承来实现的。
- 缺点:
- 需要进行强制类型转换
- 可向集合中添加任意类型的对象,存在风险。
泛型的使用
方式一:
List<String> list=new ArrayList<String>();
方式二:
在JavaSE7以后的版本中,构造方法中可以省略泛型类型。
List<String> list=new ArrayList<>();
多态与泛型
错误例子:
- class Animal{}
- class Cat extends Animal{}
- List list = new ArrayList();
//变量声明的类型必须匹配传递给实际对象的类型
主要内容
- 泛型作为方法参数
- 自定义泛型类
- 自定义泛型方法
泛型作为方法参数
定义子类:
package com.imooc.generic;
public class Book extends Goods {
@Override
public void sell() {
System.out.println("sell books");
}
}
定义泛型方法:
package com.imooc.generic;
import java.util.List;
public class GoodsSeller {
public void sellGoods(List<? extends Goods> goods){
//调用集合中的sell方法
for(Goods g:goods){
g.sell();
}
}
}
定义主方法:
package com.imooc.generic;
import java.util.ArrayList;
import java.util.List;
public class GoodsTest {
public static void main(String[] args) {
//定义book相关的List
List<Book> books=new ArrayList<Book>();
books.add(new Book());
books.add(new Book());
//定义chothes相关的List
List<Clothes> clothes=new ArrayList<Clothes>();
clothes.add(new Clothes());
clothes.add(new Clothes());
//定义shoes相关的List
List<Shoes> shoes=new ArrayList<>();
shoes.add(new Shoes());
shoes.add(new Shoes());
GoodsSeller goodsSeller=new GoodsSeller();
goodsSeller.sellGoods(books);
goodsSeller.sellGoods(clothes);
goodsSeller.sellGoods(shoes);
}
}
//运行结果:
sell books
sell books
sell clothes
sell clothes
sell shoes
sell shoes
自定义泛型类
在类名称后面加上<>,T是创建对象时传入的的对象类型。
package com.imooc.generic;
public class NumGeneric<T> {
private T num;
public T getNum(){
return num;
}
public void setNum(T num){
this.num=num;
}
//测试
public static void main(String[] args){
NumGeneric<Integer> intNum=new NumGeneric<>();
intNum.setNum(10);
System.out.println("Integer:"+intNum.getNum());
NumGeneric<Float> floatNum=new NumGeneric<>();
floatNum.setNum(5.0f);
System.out.println("Float:"+floatNum.getNum());
}
}
自定义泛型方法
在访问修饰符public和返回值void中间加上<>
package com.imooc.generic;
public class GenericMethod {
public <T extends Number> void printValue(T t){
System.out.println(t);
}
public static void main(String[] args){
GenericMethod gm=new GenericMethod();
gm.printValue(123);
gm.printValue(5.0f);
}
}
//运行结果
123
5.0