The List Interface
Recall that DynamicArray and LinkedList support the same operations:
public class DynamicArray<T> {
// ...
public void add(T element) { ... }
public T remove(int index) { ... }
public boolean remove(T element) { ... }
public void set(int index, T element) { ... }
public T get(int index) { ... }
public boolean contains(T element) { ... }
public int indexOf(T element) { ... }
public int size() { ... }
}
public class LinkedList<T> {
// ...
public void add(T element) { ... }
public T remove(int index) { ... }
public boolean remove(T element) { ... }
public void set(int index, T element) { ... }
public T get(int index) { ... }
public boolean contains(T element) { ... }
public int indexOf(T element) { ... }
public int size() { ... }
}
We designed both classes to support the operations we expect of a list. That shared set of operations is the kind of contract we want to extract into an interface. An interface defines a contract that says, “If you are a List, you must support these operations.”
Here is the interface for our list classes:
public interface List<T> {
void add(T element);
boolean remove(T element);
void set(int index, T element);
T get(int index);
boolean contains(T element);
int indexOf(T element);
int size();
}
An interface looks a lot like a class, with a few differences. It uses the interface keyword instead of class. It also only contains method declarations, not method bodies. Each method signature ends with a semicolon instead of a block of code.
Interfaces in Modern Java
Modern Java allows interfaces to contain more than method declarations, including default and static methods with bodies. In this course, we will use interfaces only to declare operations, without providing implementations.
I also decided to drop the overloaded remove(int index) method from the interface. I did this only to keep the interface small.