Java 教程是为 JDK 8 编写的。本页中描述的示例和实践未利用在后续版本中引入的改进。
Java 集合框架旨在确保核心 集合接口 与用于在 Java 平台早期版本中表示集合的类型之间的完全互操作性:Vector,Hashtable,array 和 Enumeration。在本节中,你将学习如何将旧集合转换为 Java 集合框架集合,反之亦然。
假设你正在使用一个返回旧集合 API,该 API 与另一个需要实现集合接口的对象的 API 一起使用。为了使两个 API 顺利地互操作,你必须将旧版集合转换为现代集合。幸运的是,Java 集合框架使这很容易。
假设旧 API 返回一个对象数组,新 API 需要 Collection。集合框架有一个便利实现,允许将数组对象视为 List。使用 Arrays.asList 将数组传递给需要 Collection 或 List 的任何方法。
Foo[] result = oldMethod(arg); newMethod(Arrays.asList(result));
如果旧 API 返回 Vector 或 Hashtable,则根本没有工作要做,因为 Vector 被改进以实现 List 接口且 Hashtable 进行了改进,以实现 Map。因此,Vector 可以直接传递给任何调用 Collection 或 List 的方法。
Vector result = oldMethod(arg); newMethod(result);
类似地,Hashtable 可以直接传递给任何调用 Map 的方法。
Hashtable result = oldMethod(arg); newMethod(result);
不太常见的是,API 可能会返回表示对象集合的 Enumeration。Collections.list 方法将 Enumeration 转换为 Collection。
Enumeration e = oldMethod(arg); newMethod(Collections.list(e));
假设你正在使用一个返回现代集合 API,该 API 与另一个要求你传入旧集合的 API 一起使用。要使两个 API 平滑地互操作,你必须将现代集合转换为旧集合。同样,Java 集合框架使这一过程变得简单。
假设新 API 返回 Collection,旧 API 需要 Object 数组。你可能知道,Collection 接口包含为此情况明确设计的 toArray 方法。
Collection c = newMethod(); oldMethod(c.toArray());
如果旧 API 需要 String(或其他类型)数组而不是 Object 数组,该怎么办?你只需使用另一种形式的 toArray 在输入上采用数组的那个。
Collection c = newMethod(); oldMethod((String[]) c.toArray(new String[0]));
如果旧 API 需要 Vector,则标准集合构造函数会派上用场。
Collection c = newMethod(); oldMethod(new Vector(c));
旧 API 需要 Hashtable 的情况类似地处理。
Map m = newMethod(); oldMethod(new Hashtable(m));
最后,如果旧 API 需要 Enumeration,你会怎么做?这种情况并不常见,但它确实经常发生,并且提供了 Collections.enumeration 方法来处理它。这是一个静态工厂方法,它接受 Collection 并在 Collection 的元素上返回 Enumeration。
Collection c = newMethod(); oldMethod(Collections.enumeration(c));