Java Best Practice: Return a List, not a LinkedList

By | March 18, 2022
Java Best Practice: Return a List, not a LinkedList

Java List is used to store an array of similar objects, for example, groups of numbers, categories of fruits, a list of names, etc. There are many applications of different list types in Java. LinkedList and ArrayList are the popular types of lists used in Java. It is common for us to pre-define a return type, but it is not a Java best practice. We will see why in the below section.

Returning a Java Collection and not specific List type

One of the Java best practices is to return general object references rather than specific types. The most common example is returning List in place of LinkedList or ArrayList. Or better, return a Collection object instead of List!

Collection ? List ? LinkedList

? ArrayList

Let us see an example where we are returning the specific ArrayList:

private ArrayList<String> getArrayList() {
ArrayList<String> arr = new ArrayList<String>();
return arr;

Same thing can be done with LinkedList:

private LinkedList<String> getLinkedList() {
List<String> linked = new LinkedList<String>();
return (LinkedList<String>) linked;

Note that in the above code example, we have to cast the return value to LinkedList; otherwise, there will be a type mismatch between List and LinkedList. We can do the same using the Collection interface or the List interface.

private Collection<String> getCollectionValues() {
Collection<String> collection = new ArrayList<String>();
return collection;

Note that we will not get the type mismatch error now because we are moving from specific to the general type and not the other way round. That’s the reason why it is recommended to use general types.

Make sure that when you are returning general references, the interfaces should support those methods. This way, any developer who doesn’t need to know details about your code doesn’t have to worry about the specific type.



Having to return an interface makes your code more usable and general. To know more, it will be worthwhile to read Javadoc of Collection and List interfaces to understand the methods supported by each.

People are also reading: 

Author: Ramya Shankar

A cheerful, full of life and vibrant person, I hold a lot of dreams that I want to fulfill on my own. My passion for writing started with small diary entries and travel blogs, after which I have moved on to writing well-researched technical content. I find it fascinating to blend thoughts and research and shape them into something beautiful through my writing.

Leave a Reply

Your email address will not be published.