Java Reference
In-Depth Information
NOTE When you have code where you know you will get a compiler warning that you are
going to ignore, you can prevent the warning being issued by using an annotation. The an-
notation can be placed before the definition of a method that causes the warning or before
a class definition. You could place the following line immediately preceding the TrySerializ-
ableLinkedList class definition to prevent the unchecked cast warning being issued:
@SuppressWarnings("unchecked")
The identifier for the warning message you want to suppress goes between the parentheses.
It appears in the warning message between square brackets. You should only use this to sup-
press warnings you are sure are redundant for your code.
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 is 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 look at practical example.
Enabling the Collection-Based for Loop for a Container Class
The for loop that you have been using to extract the elements stored in a linked list, such as in the TryAuto-
boxing example at the beginning of this chapter, 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 to implement, 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 java.lang.Iterable<> interface. The Iter-
able<T> interface is a generic type that declares a single method, iterator() , that returns a reference of
type Iterator<T> . All your class has to do then is to declare that it implements the Iterable<T> interface
and provide an implementation for the iterator() method.
Here's the outline of what you need to add to the LinkedList<> generic type that you developed at the
beginning of this chapter to make it usable with the collection-based for loop:
import java.util.Iterator;
public class LinkedList<T> implements Iterable<T> {
// Returns an iterator for this list
public Iterator<T> iterator() {
// Code to return an Iterator<T> reference for this list...
}
// Rest of the LinkedList<T> generic type definition as before...
Search WWH ::




Custom Search