Java Best Practice: Return a List, not a LinkedList

Posted in /  

Java Best Practice: Return a List, not a LinkedList

Ramya Shankar
Last updated on May 22, 2024

    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:

    Leave a Comment on this Post