Java Reference
In-Depth Information
them in the same order that you created them. Figure 7-2 is a diagram showing the normal
arrangement.
Figure 7-2. Linked list structure
Of course, the Collections API provides a LinkedList class; here is a simple program that
uses it:
public
public class
class LinkedListDemo
LinkedListDemo {
public
public static
void main ( String [] argv ) {
System . out . println ( "Here is a demo of Java's LinkedList class" );
LinkedList < String > l = new
static void
new LinkedList <>();
l . add ( new
new Object (). toString ());
l . add ( "Hello" );
l . add ( "end of the list" );
System . out . println ( "Here is a list of all the elements" );
ListIterator li = l . listIterator ( 0 );
while
while ( li . hasNext ())
System . out . println ( "Next to: " + li . next ());
iif ( l . indexOf ( "Hello" ) < 0 )
System . err . println ( "Lookup does not work" );
else
else
System . err . println ( "Lookup works" );
// Now, for added fun, let's walk the linked list backwards.
while
while ( li . hasPrevious ()) {
System . out . println ( "Back to: " + li . previous ());
}
Search WWH ::




Custom Search