兼容性
原文: https://docs.oracle.com/javase/tutorial/collections/interoperability/compatibility.html
Java Collections Framework 旨在确保核心集合接口与用于在 Java 平台早期版本中表示集合的类型之间的完全互操作性: Vector , Hashtable ,阵列和 Enumeration 。在本节中,您将学习如何将旧集合转换为 Java 集合框架集合,反之亦然。
向上兼容性
假设您正在使用一个 API,该 API 与另一个需要实现集合接口的对象的 API 一起返回旧集合。为了使两个 API 顺利地互操作,您必须将旧版集合转换为现代集合。幸运的是,Java Collections Framework 使这很容易。
假设旧 API 返回一个对象数组,新 API 需要Collection。 Collections Framework 有一个方便的实现,允许将一组对象视为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 Collections Framework 使这一过程变得简单。
假设新 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));
