13.3. Generic Types and Generic Interfaces

A generic type can implement one or more interface types, including generic interface types. The syntax that you use for this is the same as for ordinary class and interface types, the only difference being that each generic type name will be followed by its type parameter list between angled brackets. For example:

public class MyClass<T> implements MyInterface<T> {
  // Details of the generic type definitions
}

You can see how this works by taking a practical example.

13.3.1. Enabling the Collection-Based for Loop

The for loop you have been using to extract the elements stored in a linked list, such as in the TryAutoboxing example at the beginning of this chapter, for example, was rather cumbersome. Wouldn't it be nice if you could use the collection-based for loop with the classes produced from the LinkedList<> generic type? It's not that difficult, so let's see how to do it.

For an object of a container class type to be usable with the collection-based for loop, the class must fulfill just one requirement—it must implement the generic Iterable<> interface that is defined in the java.lang package. The Iterable<> interface is a generic type that declares a single method, iterator(), that returns a reference of type Iterator<>, which is another generic interface type. All your class has to do then is declare that it implements the Iterable<> interface and provide an implementation for the iterator() method.

Here's the outline of what you ...

Get Ivor Horton's Beginning Java™ 2, JDK™ 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.