Java: Collections.list for iterator / iterable
Why is java.util.Collections.list
only for Enumeration
but not for Iterator
(or Iterable
)? Or why is there not an overload of this function for Iterator
(or Iterable
)? Is there any other method which doe开发者_JAVA百科s that? Is there any reason why that is?
Noone really answered it yet, so here I go:
When it what introduced, there probably was no Iterable
yet. Now, it is obsolete (constructors of most Collection
implementations provide the same thing) and just stays there for backward compatibility.
From the JavaDoc:
Returns an array list containing the elements returned by the specified enumeration in the order they are returned by the enumeration. This method provides interoperability between legacy APIs that return enumerations and new APIs that require collections.
If you have a Collection and want to make new List based on that collection, you can use constructors or the addAll()
method. This method is somthing like an adapter provided by the collections framework.
For custom iterables you can use the enhanced for loop to copy the elements returnd by an iterator to an existing list.
it's purpose is to provide interoperability between legacy APIs that return enumerations and new APIs that require collections
精彩评论