没有泛形的Collections 库的代码

ArrayList list = new ArrayList();
list.add(0, new Integer(42));
 
int total = ((Integer)list.get(0)).intValue();

带有范型化Collections 库的同一个例子可编写为:

ArrayList<Integer> list =  new ArrayList<Integer>();
list.add(0, new Integer(42));
int total = list.get(0).intValue();
范型化 API 的用户必须使用 <> 符号简单地声明在编译类型中使用的类型

增强的 for 循环

Collections API 经常使用 Iterator 类。Iterator 类提供在 Collection 中顺序导航的机制。

当像下面一样只是在 Collection 中遍历时,新的增强的 for 循环可取代 iterator。

编译器生成必要的循环代码,因为利用范型,所以不需要额外的类型转换。

原来

ArrayList<Integer> list = new ArrayList<Integer>();
for (Iterator i = list.iterator(); i.hasNext();) {
Integer value=(Integer)i.next();
}

现在

ArrayList<Integer> list = new ArrayList<Integer>();
for (Integer i : list) { ... }


相关文章:

  • 2021-07-05
  • 2022-01-03
  • 2022-01-22
  • 2021-10-18
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-04-13
  • 2022-12-23
  • 2021-10-01
  • 2022-12-23
相关资源
相似解决方案