Java Reference
In-Depth Information
Display 15.10
A Generic Linked List Demonstration (part 2 of 2)
14 list.outputList( );
15 System.out.println("End of list.");
16 }
17 }
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 defi ning 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 specifi cation <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 mes-
sage, 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; if you do get a bewildering compiler error
message, look for a missing <T> .
Sometimes a compiler warning message can be helpful when you make this mistake.
If you get a warning that mentions a type cast from Node to Node<T> , look for an
omitted <T> .
Finally, we should note that sometimes your code will compile and even run cor-
rectly if you omit the <T> from Node<T> .
The equals Method for Linked Lists
The linked lists we presented in Display 15.3 and 15.7 do not have an equals method.
We did that to keep the examples simple and not detract from the main message.
However, a linked list class should normally have an equals method.
There is more than one approach to defining a reasonable equals method for a
linked list. The two most obvious are the following:
1. Two linked lists are equal if they contain the same data entries (possibly ordered
differently).
equals
 
 
Search WWH ::




Custom Search