【Java 16】泛型 - 集合中使用泛型、自定义泛型结构、泛型在继承上的体现、通配符

本文详细介绍了Java中的泛型,包括为什么引入泛型、如何在集合中使用泛型以提高类型安全性,自定义泛型类和接口、泛型方法的实现,以及泛型在继承中的体现。还探讨了通配符的使用,如无限制和有限制的通配符,并通过例子展示了泛型的实际应用。建议在实例化泛型类时指定类型,以充分利用泛型的优势。
摘要由CSDN通过智能技术生成

泛型

image-20200830022101047

1 为什么要有泛型

image-20200830111616049

image-20200830111622369

image-20200830111627833

image-20200830111632228

2 在集合中使用泛型

ArrayList<Integer> list = new ArrayList<>();//jdk7新特性, 类型推断

list.add(78);
list.add(88);
list.add(77);
list.add(66);

//遍历方式一:
for(Integer i : list){
   
	//不需要强转
	System.out.println(i);
}

//遍历方式二:
Iterator<Integer> iterator = list.iterator();
while(iterator.hasNext()){
   
	System.out.println(iterator.next());
}
Map<String,Integer> map = new HashMap<String,Integer>();

map.put("Tom1",34);
map.put("Tom2",44);
map.put("Tom3",33);
map.put("Tom4",32);
//添加失败
//map.put(33, "Tom");

Set<Entry<String,Integer>> entrySet = map.entrySet();

Iterator<Entry<String,Integer>> iterator = entrySet.iterator();

while(iterator.hasNext()){
   
	Entry<String,Integer> entry = iterator.next();
	System.out.println(entry.getKey() + "--->" + entry.getValue());
}
  1. 集合接口或集合类在jdk5.0时都修改为带泛型的结构

  2. 在实例化集合类的时候,可以指明泛型类型

  3. 指明完以后,在集合类或接口中凡是定义类或接口时,内部结构使用类的泛型的位置,都指定为实例化的泛型类型

  4. 注意点:泛型的类型必须是类,不能是基本数据类型。需要用到基本数据类型的位置,使用包装类封装

  5. 如果实例化时,没有指明泛型的类型。默认类型为java.lang.Object类型

  6. 自然排序

    image-20200830195900648

    定制排序

    image-20200830200147775

3 自定义泛型

image-20200830200957182

image-20200830201029741

3.1 泛型类、泛型接口

image-20200830201057532

image-20200830203344645

image-20200830204618572

image-20200830204628431

如果定义了泛型类,实例化没有指明类的泛型,则认为此泛型类型为Object类型

要求:如果大家定义了类是带泛型的,建议在实例化时要指明类的泛型

public class Order<T>{
   
    
    String orderName;
    int orderId;
    
    T orderT;
    
    public Order(){
   
        //编译不通过
        //T[] arr = new T[10];
        T[] arr = (T[])new Object[10];
        
    }
    
    public Order(String orderName, int orderId, T orderT){
   
        this.orderName = orderName;
        this.orderId = orderId;
        this.orderT = orderT;
    }
    
    public T getOrderT{
   
        return orderT;
    }
    
    public void setOrderT(T orderT){
   
        this
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值