版权声明:未经允许,随意转载,请附上本文链接谢谢(づ ̄3 ̄)づ╭❤~
http://blog.csdn.net/xiaoduan_/article/details/79343257
泛型
为什么使用泛型
在Java中增加泛型之前,泛型程序设计使用继承来实现的
坏处:
- 需要强制转换
- 可向集合中添加任意类型的对象,存在风险。
泛型的使用
List<String> list=new ArrayList<String>();
- Java SE7及以后的版本中,构造方法中可以省略泛型类型。
例如:List<String> list=new ArrayList<>();
多态与泛型
- 变量声明的类型必须匹配传递给实际对象的类型,父类,子类都不可以
下面是错误的例子
List<Animal> list=new ArrayList<Cat>();//错误的例子
List<Object> list=new ArrayList<String>();//错误的例子
List<Number> numbers=new ArrayList<Integer>();//错误的例子
泛型可以作为方法参数
<? extends Goods>
extends后面的内容也可以接接口 表示继承Goods的对象<? super Goods>
表示Goods的父类
import java.util.List;
public class GoodsSeller {
public void sellGoods(List<? extends Goods> goods){
//调用集合中的sell方法
for(Goods g:goods){
g.sell();
}
}
}
泛型注意问题
- 泛型的类型参数只能是类类型,不能是基本数据类型
比如:List<Integer> list=new ArrayList<Integer>();
- 泛型的原理就是参数化类型
例子
import java.util.ArrayList;
import java.util.List;
public class GoodsTest {
public static void main(String[] args) {
//定义book相关的List
//泛型限定了传入的类型必须是Book类型
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);
}
}