Java Reference
In-Depth Information
0 removed
The list is: -1 1 5
-1 removed
The list is: 1 5
5 removed
The list is: 1
1 removed
Empty list
Fig. 21.5 | ListTest class to demonstrate List capabilities. (Part 2 of 2.)
21.4.3 Generic Classes ListNode and List
Generic class ListNode (Fig. 21.3, lines 6-37) declares package-access fields data and
nextNode . The data field is a reference of type T , so its type will be determined when the
client code creates the corresponding List object. Variable nextNode stores a reference to
the next ListNode object in the linked list (or null if the node is the last one in the list).
Lines 42-43 of class List (Fig. 21.3, lines 40-47) declare references to the first and
last ListNode s in a List ( firstNode and lastNode , respectively). The constructors (lines
47-50 and 53-57) initialize both references to null . The most important methods of class
List are insertAtFront (lines 60-66), insertAtBack (lines 69-75), removeFromFront
(lines 78-92) and removeFromBack (lines 95-118). Method isEmpty (lines 121-124) is a
predicate method that determines whether the list is empty (i.e., the reference to the first
node of the list is null ). Predicate methods typically test a condition and do not modify
the object on which they're called. If the list is empty, method isEmpty returns true ; oth-
erwise, it returns false . Method print (lines 127-146) displays the list's contents. We
discuss class List 's methods in more detail after we discuss class ListTest .
21.4.4 Class ListTest
Method main of class ListTest (Fig. 21.5) creates a List<Integer> object (line 10), then
inserts objects at the beginning of the list using method insertAtFront , inserts objects at
the end of the list using method insertAtBack , deletes objects from the front of the list
using method removeFromFront and deletes objects from the end of the list using method
removeFromBack . After each insert and remove operation, ListTest calls List method
print to display the current list contents. If an attempt is made to remove an item from
an empty list, an EmptyListException (Fig. 21.4) is thrown, so the method calls to re-
moveFromFront and removeFromBack are placed in a try block that's followed by an ap-
propriate exception handler. Notice in lines 13, 15, 17 and 19 (Fig. 21.5) that the
application passes literal primitive int values to methods insertAtFront and insertAt-
Back . Each of these methods was declared with a parameter of the generic type T
(Fig. 21.3, lines 60 and 69). Since this example manipulates a List<Integer> , the type T
represents the type-wrapper class Integer . In this case, the JVM autoboxes each literal val-
ue in an Integer object, and that object is actually inserted into the list.
21.4.5 List Method insertAtFront
Now we discuss each method of class List (Fig. 21.3) in detail and provide diagrams
showing the reference manipulations performed by methods insertAtFront , insertAt-
 
 
 
 
Search WWH ::




Custom Search