26.07.2013 Views

Java How to Program Fourth Edition - DCC

Java How to Program Fourth Edition - DCC

Java How to Program Fourth Edition - DCC

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

1102 Data Structures Chapter 19<br />

146 return firstNode == null;<br />

147 }<br />

148<br />

149 // output List contents<br />

150 public synchronized void print()<br />

151 {<br />

152 if ( isEmpty() ) {<br />

153 System.out.println( "Empty " + name );<br />

154 return;<br />

155 }<br />

156<br />

157 System.out.print( "The " + name + " is: " );<br />

158<br />

159 ListNode current = firstNode;<br />

160<br />

161 // while not at end of list, output current node's data<br />

162 while ( current != null ) {<br />

163 System.out.print( current.data.<strong>to</strong>String() + " " );<br />

164 current = current.nextNode;<br />

165 }<br />

166<br />

167 System.out.println( "\n" );<br />

168 }<br />

169<br />

170 } // end class List<br />

Fig. Fig. 19.3 19.3 Definitions of class ListNode and class List (part 4 of 4).<br />

Class List contains private members firstNode (a reference <strong>to</strong> the first<br />

ListNode in a List) and lastNode (a reference <strong>to</strong> the last ListNode in a List).<br />

The construc<strong>to</strong>rs (lines 47–51 and 54–57) initialize both references <strong>to</strong> null. The most<br />

important methods of class List are the synchronized methods insertAtFront<br />

(lines 62–69), insertAtBack (lines 74–82), removeFromFront (lines 85–106) and<br />

removeFromBack (lines 109–141). These methods are declared synchronized so<br />

List objects can be multithread safe when used in a multithreaded program. If one thread<br />

is modifying the contents of a List, no other thread can modify the same List object at<br />

the same time. Method isEmpty (lines 144–147) is a predicate method that determines<br />

whether the list is empty (i.e., the reference <strong>to</strong> the first node of the list is null). Predicate<br />

methods typically test a condition and do not modify the object on which they are called. If<br />

the list is empty, method isEmpty returns true; otherwise, it returns false. Method<br />

print (lines 150–168) displays the list’s contents. Both isEmpty and print are also<br />

synchronized methods.<br />

1 // Fig. 19.4: EmptyListException.java<br />

2 // Class EmptyListException definition<br />

3 package com.deitel.jhtp4.ch19;<br />

4<br />

5 public class EmptyListException extends RuntimeException {<br />

6<br />

Fig. Fig. Fig. 19.4 19.4 Definition of class EmptyListException (part 1 of 2).

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!