O'Reilly logo

Ivor Horton's Beginning Java™ 2, JDK™ 5th Edition by Ivor Horton

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required