Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Is there a good reason that the Collections.list() method in the java.utils package returns an ArrayList<T> instead of List<T>?

Obviously an ArrayList is a List, but I'm under the impression that it's generally good practice to return the interface type instead of implementation type.

like image 967
Tianxiang Xiong Avatar asked Sep 02 '15 15:09

Tianxiang Xiong


People also ask

Can we use enumeration on ArrayList?

In order to get enumeration over ArrayList with Java Collections, we use the java. util. Collections. enumeration() method.

How do you enumerate a list in Java?

Enumeration[] array = Enumeration. values(); List<Enumeration> list = Arrays. asList(array);

What would be the best choice instead of ArrayList to generalize this function?

Explanation: Collections have subinterfaces called lists. It is possible to store duplicate values in this ordered collection of objects.

Should I return list or ArrayList Java?

It's best to return the most generic type that's appropriate for your interface. Show activity on this post. For types like List or ArrayList there shouldn't be any complication and you should return List promoting code to an interface.


1 Answers

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); 
like image 128
durron597 Avatar answered Oct 20 '22 01:10

durron597