• 容器中使用泛型


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

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

    1
    2
    3
    4
    5
    6
    7
    8
    9
    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接口都定义了泛型,如下图所示:

    图9-2容器的泛型定义.png

          因此,我们在使用这些接口及其实现类时,都要使用泛型。

    菜鸟雷区

          我们只是强烈建议使用泛型。事实上,不使用编译器也不会报错!

  • 相关阅读:
    作业3
    学习进度
    作业2
    介绍自己,并介绍github注册过程和初步使用
    mysql显示中文乱码问题解决
    数学能力测试
    C++ Primer总结
    shell脚本
    完全二叉树
    test命令的测试功能
  • 原文地址:https://www.cnblogs.com/huaxiansheng/p/15317749.html
Copyright © 2020-2023  润新知