Java Reference
In-Depth Information
Display 15.10 A Generic Linked List Demonstration
1 public class GenericLinkedListDemo
2{
3
public static void main(String[] args)
4
{
5
LinkedList3<Entry> list = new LinkedList3<Entry>( );
6
7
Entry entry1 = new Entry("Apples", 1);
8
list.addToStart(entry1);
9
Entry entry2 = new Entry("Bananas", 2);
10
list.addToStart(entry2);
11
Entry entry3 = new Entry("Cantaloupe", 3);
12
list.addToStart(entry3);
13
System.out.println("List has " + list.size( )
14
+ " nodes.");
15
list.outputList( );
16
System.out.println("End of list.");
17
}
18
}
Sample Dialogue
List has 3 nodes.
Cantaloupe 3
Bananas 2
Apples 1
End of list.
PITFALL: Using Node Instead of Node<T>
This pitfall is explained by example, using the LinkedList3<T> class in Display 15.8.
However, the lesson applies to any generic linked structure with a node inner class.
The type parameter need not be T and the node class name need not be Node , but for
simplicity, we will use T and Node .
When defining the LinkedList3<T> class in Display 15.8, the type for a node is
Node<T> ; it is not Node . However, it is easy to forget the type specification <T> and
write Node instead of Node<T> . If you omit the <T> , you may or may not get a compiler
error message, depending on other details of your code. If you do get a compiler error
message, it is likely to seem bewilderingly strange. The problem is that Node actually
means something. (We do not have time to stop and explain what Node means, but it
means something similar to a node with data type Object , rather than data type T .)
Your only defense against this pitfall is to be very careful, and if you do get a bewilder-
ing compiler error message, look for a missing <T> .
 
Search WWH ::




Custom Search