Java Best Practice: Return a List, not a LinkedList

By | September 29, 2021
Java Best Practice: Return a List, not a LinkedList

Introduction

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!

Vamware

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>();
arr.add("one");
arr.add("two");
arr.add("one");
arr.add("three");
return arr;
}

Same thing can be done with LinkedList:

private LinkedList<String> getLinkedList() {
List<String> linked = new LinkedList<String>();
linked.add("one");
linked.add("two");
linked.add("one");
linked.add("three");
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>();
collection.add("one");
collection.add("two");
collection.add("one");
collection.add("three");
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.

Conclusion

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: 

Leave a Reply

Your email address will not be published. Required fields are marked *