Java中的泛型

xiaoxiao2021-02-28  40

1.在集合中不使用泛型 public static void main(String[] args) { List list = new ArrayList(); list.add(89); list.add(87); list.add(67); // 1.没有使用泛型,任何Object及其子类的对象都可以添加进来 list.add(new String("AA")); for (int i = 0; i < list.size(); i++) { // 2.强转为int型时,会报ClassCastException的异常 int score = (Integer) list.get(i); System.out.println(score); } } 2.在集合中使用了泛型 public void test2(){ public static void main(String[] args) { List<Integer> list = new ArrayList<Integer>(); list.add(78); list.add(87); // 向list中添加字符串类型会报错,只能添加指定的泛型类型 // list.add("AA"); // 两种遍历方法 for (int i = 0; i < list.size(); i++) { int score = list.get(i); System.out.println(score); } Iterator<Integer> it = list.iterator(); while (it.hasNext()) { System.out.println(it.next()); } } } 3.自定义泛型类:最常用的就是通用DAO public class DAO<T> { public void add(T t){ //.... } public T get(int index){ return null; } public List<T> getForList(int index){ return null; } public void delete(int index){ } } public class CustomerDAO extends DAO<Customer>{ } public class TestCustomerDAO { public static void main(String[] args) { CustomerDAO c = new CustomerDAO(); c.add(new Customer()); c.get(0); } } 注意:     1.对象实例化时不指定泛型,默认为:Object。     2.泛型不同的引用不能相互赋值。     3.加入集合中的对象类型必须与指定的泛型类型一致。     4.静态方法中不能使用类的泛型。     5.如果泛型类是一个接口或抽象类,则不可创建泛型类的对象。     6.不能在catch中使用泛型     7.从泛型类派生子类,泛型类型需具体化 4.泛型与继承的关系 A类是B类的子类,G是带泛型声明的类或接口。那么G<A>不是G<B>的子类! 5.通配符:? A类是B类的子类,G是带泛型声明的类或接口。则G<?> 是G<A>、G<B>的父类! ①以List<?>为例,能读取其中的数据。因为不管存储的是什么类型的元素,其一定是Object类的或其子类的。 ①以List<?>为例,不可以向其中写入数据。因为没有指明可以存放到其中的元素的类型!唯一例外的是:null 6*.  List<? extends A> :可以将List<A>的对象或List<B>的对象赋给List<? extends A>。其中B 是A的子类

       ? super A:可以将List<A>的对象或List<B>的对象赋给List<? extends A>。其中B 是A的父类

转载请注明原文地址: https://www.6miu.com/read-2622484.html

最新回复(0)