Java--容器中使用泛型

2022-10-18  本文已影响0人  李赫尔南

  容器相关类都定义了泛型,我们在开发和工作中,在使用容器类时都要使用泛型。这样,在容器的存储数据、读取数据时都避免了大量的类型判断,非常便捷。

【示例】泛型类的在集合中的使用

public class Test {
    public static void main(String[] args) {
        //以下代码中List、Set、Map、Iterator都是与容器相关的接口;
        List<String> list = new ArrayList<String>();
        Set<Man> mans = new HashSet<Man>();
        Map<Integer, Man> maps = new HashMap<Integer, Man>();
        Iterator<Man> iterator = mans.iterator();
    }
}

  通过阅读源码,我们发现Collection、List、Set、Map、Iterator接口都定义了泛型,如下图所示:


容器的泛型定义.png
上一篇 下一篇

猜你喜欢

热点阅读