Java Collections Framework旨在确保核心集合接口和Java平台早期版本中用于表示集合的类型(VectorHashtablearrayEnumeration)之间具有完全的互操作性。 在本部分中,您将学习如何将旧的集合转换为Java Collections Framework集合,反之亦然。

向上兼容性

假设您正在使用一个API,该API与另一个需要对象实现集合接口的API串联返回旧集合。为了使两个API顺利互操作,您必须将旧版集合转换为现代集合。幸运的是,Java Collections Framework使这变得容易。
假设旧的API返回一个对象数组,而新的API需要一个Collection。集合框架具有方便的实现,该实现允许将对象数组视为List。您可以使用Arrays.asList将数组传递给需要CollectionList的任何方法。

  1. Foo[] result = oldMethod(arg);
  2. newMethod(Arrays.asList(result));

如果旧的API返回VectorHashtable,则根本不需要做任何工作,因为Vector进行了改进以实现List接口,而Hashtable进行了改进以实现Map。因此,可以将Vector直接传递给任何调用CollectionList的方法。

  1. Vector result = oldMethod(arg);
  2. newMethod(result);

类似地,可以将Hashtable直接传递给任何调用Map的方法。

  1. Hashtable result = oldMethod(arg);
  2. newMethod(result);

API可能不经常返回代表Enumeration对象的集合。Collections.list方法将Enumeration转换为Collection

  1. Enumeration e = oldMethod(arg);
  2. newMethod(Collections.list(e));

向后兼容

假设您使用的API会一并返回现代集合,而另一个API则要求您传入旧集合。为了使两个API顺利互操作,您必须将现代集合转换为旧集合。同样,Java Collections Framework使这变得容易。
假设新API返回Collection,而旧API需要一个数组Object。您可能已经知道,Collection接口包含专门针对这种情况设计的toArray方法。

  1. Collection c = newMethod();
  2. oldMethod(c.toArray());

如果旧的API需要数组String(或其他类型)而不是数组Object怎么办?您只需要使用另一种形式toArray——在输入中采用数组。

  1. Collection c = newMethod();
  2. oldMethod((String[]) c.toArray(new String[0]));

如果旧的API需要使用Vector,则标准集合构造函数将派上用场。

  1. Collection c = newMethod();
  2. oldMethod(new Vector(c));

类似地处理旧的API需要Hashtable的情况。

  1. Map m = newMethod();
  2. oldMethod(new Hashtable(m));

最后,如果旧的API需要输入Enumeration,该怎么办?这种情况并不常见,但确实会不时发生,并且提供了处理该问题的Collections.enumeration方法。这是一个静态工厂方法,采用Collection并在Collection的元素上返回Enumeration

  1. Collection c = newMethod();
  2. oldMethod(Collections.enumeration(c));