Why does Enumeration get converted to ArrayList and not List in java.utils?

Disclaimer: I am not a JDK author.

I agree that it’s correct to write your own code to interfaces, but if you’re going return a mutable collection to a third party, it’s important to let the third party know what sort of List they’re getting back.

LinkedList and ArrayList are very different, performance wise, for various operations. For example, removing the first element of an ArrayList is O(n), but removing the first element of a LinkedList is O(1).

By fully specifying the return type, the JDK authors are communicating extra information, in unambiguous code, about what sort of object they’re giving back to you, so you can write your code to use this method properly. If you really need a LinkedList, you know that you have to specify one here.

Finally, the main reason to code to an interface over an implementation is if you think that the implementation will change. The JDK authors probably figure they are never going to change this method; it’s never going to return a LinkedList or a Collections.UnmodifiableList. However, in most cases, you would probably still do:

List<T> list = Collections.list(enumeration);

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)