Search code examples
javamethodsinterfacereturn-type

How to return an interface from a method


Here is my method. I want to return a collection of strings from a Java method. I would like for the calling code to decide whether it wants to implement this collection as a Vector or a LinkedList or an ArrayList or something else that implements the List interface.

public List<String> findAvailableLanguages() {
    Iterator<Map.Entry<String, String>> it = this.iterator();
    List<String> list = new ArrayList<String>();
    while (it.hasNext()) {
        Map.Entry<String, String> n = it.next();
        list.add(n.getKey());
    }

...

However, I must instantiate a concrete class object inside of the method in order to build the collection. What do I now return that will be compatible with any class that implements List?

Is this possible?


Solution

  • It's more effective for the callers if you allow a List to be passed in the filling process instead of initiating your own. It will also make for code that's easily unit-testable, as this does the pattern known as Dependency Injection.

    public List<String> populateWithAvailableLanguages(List<String> list) {
        Iterator<Map.Entry<String, String>> it = this.iterator();
        // List<String> list = new ArrayList<String>();
        while (it.hasNext()) {
            Map.Entry<String, String> n = it.next();
            list.add(n.getKey());
        }
    }
    

    Now the implementation of the List can be specified by the caller:

    List<String> availableLanguages = new ArrayList<>();
    Localizer.populateWithAvailableLanguages(availableLanguages);