java泛型学习总结

1.泛型在集合中的使用(掌握)
2.自定义泛型类、泛型接口、泛型方法(理解 --->使用)
3.泛型与继承的关系
4.通配符


1.在集合中不使用泛型

public void test1(){
    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(){
    List<Integer> list = new ArrayList<Integer>();
    list.add(78);
    list.add(87);
//        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());
    }
}
public void test3(){
    Map<String,Integer> map = new HashMap<>();
    map.put("AA", 78);
    map.put("BB", 87);
    map.put("DD", 98);
    
    Set<Map.Entry<String,Integer>> set = map.entrySet();
    for(Map.Entry<String,Integer> o : set){
        System.out.println(o.getKey() + "--->" + o.getValue());
    }
}

3.自定义泛型类:应用

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);
    }
}


【注意点】

  • 对象实例化时不指定泛型,默认为:Object。
  • 泛型不同的引用不能相互赋值。
  • 加入集合中的对象类型必须与指定的泛型类型一致。
  • 静态方法中不能使用类的泛型。
  • 如果泛型类是一个接口或抽象类,则不可创建泛型类的对象。
  • 不能在catch中使用泛型
  • 从泛型类派生子类,泛型类型需具体化

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的父类
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值