Why should the interface for a Java class be preferred?

JavaCollectionsInterface

Java Problem Overview


PMD would report a violation for:

ArrayList<Object> list = new ArrayList<Object>();

The violation was "Avoid using implementation types like 'ArrayList'; use the interface instead".

The following line would correct the violation:

List<Object> list = new ArrayList<Object>();

Why should the latter with List be used instead of ArrayList?

Java Solutions


Solution 1 - Java

Using interfaces over concrete types is the key for good encapsulation and for loose coupling your code.

It's even a good idea to follow this practice when writing your own APIs. If you do, you'll find later that it's easier to add unit tests to your code (using Mocking techniques), and to change the underlying implementation if needed in the future.

Here's a good article on the subject.

Hope it helps!

Solution 2 - Java

This is preferred because you decouple your code from the implementation of the list. Using the interface lets you easily change the implementation, ArrayList in this case, to another list implementation without changing any of the rest of the code as long as it only uses methods defined in List.

Solution 3 - Java

In general I agree that decoupling interface from implementation is a good thing and will make your code easier to maintain.

There are, however, exceptions that you must consider. Accessing objects through interfaces adds an additional layer of indirection that will make your code slower.

For interest I ran an experiment that generated ten billion sequential accesses to a 1 million length ArrayList. On my 2.4Ghz MacBook, accessing the ArrayList through a List interface took 2.10 seconds on average, when declaring it of type ArrayList it took on average 1.67 seconds.

If you are working with large lists, deep inside an inner loop or frequently called function, then this is something to consider.

Solution 4 - Java

ArrayList and LinkedList are two implementations of a List, which is an ordered collection of items. Logic-wise it doesn't matter if you use an ArrayList or a LinkedList, so you shouldn't constrain the type to be that.

This contrasts with say, Collection and List, which are different things (List implies sorting, Collection does not).

Solution 5 - Java

> Why should the latter with List be used instead of ArrayList?

It's a good practice : Program to interface rather than implementation

By replacing ArrayList with List, you can change List implementation in future as below depending on your business use case.

List<Object> list = new  LinkedList<Object>(); 
/* Doubly-linked list implementation of the List and Deque interfaces. 
 Implements all optional list operations, and permits all elements (including null).*/

OR

List<Object> list = new  CopyOnWriteArrayList<Object>(); 
/* A thread-safe variant of ArrayList in which all mutative operations
 (add, set, and so on) are implemented by making a fresh copy of the underlying array.*/

OR

List<Object> list = new  Stack<Object>(); 

/* The Stack class represents a last-in-first-out (LIFO) stack of objects.*/

OR

some other List specific implementation.

List interface defines contract and specific implementation of List can be changed. In this way, interface and implementation are loosely coupled.

Related SE question:

https://stackoverflow.com/questions/383947/what-does-it-mean-to-program-to-an-interface

Solution 6 - Java

In general for your line of code it does not make sense to bother with interfaces. But, if we are talking about APIs there is a really good reason. I got small class

class Counter {
    static int sizeOf(List<?> items) {
        return items.size();
    }
}

In this case is usage of interface required. Because I want to count size of every possible implementation including my own custom. class MyList extends AbstractList<String>....

Solution 7 - Java

Properties of your classes/interfaces should be exposed through interfaces because it gives your classes a contract of behavior to use, regardless of the implementation.

However...

In local variable declarations, it makes little sense to do this:

public void someMethod() {
List theList = new ArrayList();
//do stuff with the list
}

If its a local variable, just use the type. It is still implicitly upcastable to its appropriate interface, and your methods should hopefully accept the interface types for its arguments, but for local variables, it makes total sense to use the implementation type as a container, just in case you do need the implementation-specific functionality.

Solution 8 - Java

Even for local variables, using the interface over the concrete class helps. You may end up calling a method that is outside the interface and then it is difficult to change the implementation of the List if necessary. Also, it is best to use the least specific class or interface in a declaration. If element order does not matter, use a Collection instead of a List. That gives your code the maximum flexibility.

Solution 9 - Java

Interface is exposed to the end user. One class can implement multiple interface. User who have expose to specific interface have access to some specific behavior which are defined in that particular interface.

One interface also have multiple implementation. Based on the scenario system will work with different scenario (Implementation of the interface).

let me know if you need more explanation.

Solution 10 - Java

The interface often has better representation in the debugger view than the concrete class.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjnanchetaView Question on Stackoverflow
Solution 1 - JavakolrieView Answer on Stackoverflow
Solution 2 - JavaAdamCView Answer on Stackoverflow
Solution 3 - JavaOwenView Answer on Stackoverflow
Solution 4 - JavaSCdFView Answer on Stackoverflow
Solution 5 - JavaRavindra babuView Answer on Stackoverflow
Solution 6 - JavaRastislav KomaraView Answer on Stackoverflow
Solution 7 - JavaMetroidFan2002View Answer on Stackoverflow
Solution 8 - JavaDiastrophismView Answer on Stackoverflow
Solution 9 - Javasandeep gargView Answer on Stackoverflow
Solution 10 - JavaKiruahxhView Answer on Stackoverflow