Java Reference
In-Depth Information
Abstract Data Type (ADT)
A specification of a type of data and the operations that can be performed on it.
An ADT specifies operations that can be performed on data without specifying
exactly how those operations are implemented. Linked lists and array lists are both
examples of the list ADT because they both provide the same operations, such as
storing data by index, adding and removing data at particular indexes, and so on.
In Java, ADTs are specified by interfaces. Each ADT's operations are specified by
the methods of its interface. For example, both
LinkedList
and
ArrayList
imple-
ment an interface in the
java.util
package called
List
. The
List
interface
declares all the common methods that both types of lists implement.
It's a good practice to declare any variables and parameters of a collection type
using the appropriate interface type for that ADT rather than the actual class's type.
For example, the following code declares a
LinkedList
object but stores it in a vari-
able of type
List
:
List<Integer> list = new LinkedList<Integer>();
Joshua Bloch, one of the authors of the Java Collections Framework, says that this
programming practice is “strongly recommended” because “it gives you the flexibility
to change implementations.” Note that you cannot create an object of type
List
,but
you can use
List
as the type of a variable.
You can also use the interface types for ADTs like
List
when you declare param-
eters, return types, or fields. Doing so is useful when you're writing a method that
accepts a collection as a parameter, because it means that the method will be able to
operate successfully on any collection that implements that ADT's interface. For
example, the following method can accept a
LinkedList<String>
or an
ArrayList<String>
as its actual parameter:
// returns the longest string in the given list
// pre: list.size() > 0
public static String longest(List<String> list) {
Iterator<String> i = list.iterator();
String result = i.next();
while (i.hasNext()) {
String next = i.next();
if (next.length() > result.length()) {
result = next;
}
}
return result;
}
It works with either type of list and is efficient for both. This flexibility is another
benefit of polymorphism (discussed in Chapter 9). In fact, you could make the
Search WWH ::
Custom Search