Canonical toList in java?
Is there something like this in any standard library (e.g. apache-commons, guava) ?
public static <T> List<T> toList(Iterable<T> iterable) {
if (iterable instanceof List)
return (List<T>)iterable;
if (iterable instanceof Collection)
开发者_StackOverflow return new ArrayList<T>((Collection<T>)iterable);
List<T> result = new ArrayList<T>();
for (T item : iterable)
result.add(item);
return result;
}
I don't think so, because your implementation does two completely different things:
- If the argument is a list, it returns it. The returned list will therefore be a "live view" of the argument. Changes to each of the lists are visible in the other.
- If the argument is not a list, it returns a copy of it. The returned list will be independent of the argument.
These two things are so different that no sane general-purpose library would throw them together in one method.
精彩评论