Java Reference
In-Depth Information
Display 15.14
A Generic Linked List with a Deep Copy clone Method (part 3 of 3)
61 {
62 Node<T> position = otherHead; //moves down other's list.
63 Node<T> newHead; //will point to head of the copy list.
64 Node<T> end = null ; //positioned at end of new growing list.
This definition of copyOf gives a
deep copy of the linked list.
65 //Create first node:
66 newHead =
67 new Node<T>((T)(position.data).clone( ), null );
68 end = newHead;
69 position = position.link;
70 while (position != null )
71 { //copy node at position to end of new list.
72 end.link =
73 new Node<T>((T)(position.data).clone( ), null );
74 end = end.link;
75 position = position.link;
76 }
77
return newHead;
78 }
79
80 public boolean equals(Object otherObject)
81 {
82
if (otherObject == null )
83
return false ;
84
else if (getClass( ) != otherObject.getClass( ))
85
return false ;
86 else
87 {
88 LinkedList<T> otherList = (LinkedList<T>)otherObject;
<The rest of the definition is the same as in Display 15.8. The only difference
between this definition of equals and the one in Display 15.8 is that we
have replaced the class name LinkedList3<T> with LinkedList<T> .>
89 }
<All the other methods from Display 15.8 are in the class definition,
but are not repeated in this display.>
90 public String toString( )
91 {
92 Node<T> position = head;
93 String theString = "";
94 while (position != null )
95 {
96 theString = theString + position.data + "\n";
97 position = position.link;
98 }
99
return theString;
We added a toString method so LinkedList<T>
would have all the properties we want T to have.
100 }
101 }
 
Search WWH ::




Custom Search