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

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

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接口都定义了泛型,如下图所示:

容器中使用泛型_容器类

 

 

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

菜鸟雷区

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