Executing cleanup code before a method or block of code exits. Use either a labeled break or, more
cleanly, the finally construct of the try statement covered in Chapter 12.
•
Labeled break and continue have the advantage that they transfer control to a strictly limited place. A
finally block is even stricter as to where it transfers control, and it works in all circumstances, including
exceptions. With these constructs you can write clean code without a goto.
Furious activity is no substitute for understanding.
H.H. Williams
Chapter 11. Generic Types
The problem with people who have no vices is that generally you can be pretty sure they're
going to have some pretty annoying virtues.
Elizabeth Taylor
In the Java programming language, the class Object forms the root of the class hierarchy, allowing other
classes to deal with arbitrary types of objects by declaring that they work with Object. In Chapter 3 you saw
a SingleLinkQueue class that used Cell objects to hold a reference to any Object you wanted in the
queue. This provides great flexibility, but with some inconvenience: If you know that the elements in question
are String objects, for example, then you have to cast the result of the remove method each time.
This use of Object as a generic reference is also potentially unsafethere is nothing to stop the programmer
from mistakenly adding a Number instead of a String, with the mistake only discovered at runtime when
the cast applied to remove fails and a ClassCastException is thrown. To avoid these problems you
could define different queue classes to store particular types of elements, such as
SingleLinkStringQueue or SingleLinkNumberQueue, but this has many drawbacks: It is tedious,
inefficient, and error-prone to duplicate code in this way; it is awkward to deal with an arbitrary kind of
queue; and you could end up with numerous classes that are identical except for the return and parameter
types of a few methods. Ideally, you would like to write a SingleLinkQueue that can be specialized to
contain any particular kind of object and then, for each queue object, define which type it holds. That is where
generic types come in.
To start, here's a new version of Cell declared as a generic class:
class Cell
private Cell
private E element;
public Cell(E element) {
this.element = element;
}
public Cell(E element, Cell
this.element = element;
this.next = next;
}
public E getElement() {
return element;
}
public void setElement(E element) {
this.element = element;
}
public Cell
return next;