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.
In order to get enumeration over ArrayList with Java Collections, we use the java. util. Collections. enumeration() method.
Enumeration[] array = Enumeration. values(); List<Enumeration> list = Arrays. asList(array);
Explanation: Collections have subinterfaces called lists. It is possible to store duplicate values in this ordered collection of objects.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With