Java Reference
In-Depth Information
Display 15.37
Set<T>
Class
(part 2 of 3)
20
private
Node<T> head;
21
public
Set( )
22
{
23
head =
null
;
24 }
25
/**
26
Add a new item to the set. If the item
27
is already in the set, false is returned;
28
otherwise, true is returned.
29
*/
30
public boolean
add(T newItem)
31 {
32
if
(!contains(newItem))
33
{
34
head =
new
Node<T>(newItem, head);
35
return true
;
36
}
37
return false
;
38
}
39
public boolean
contains(T item)
40 {
41 Node<T> position = head;
42 T itemAtPosition;
43
while
(position !=
null
)
44 {
45 itemAtPosition = position.data;
46
if
(itemAtPosition.equals(item))
47
return true
;
48 position = position.link;
49 }
50
return false
;
//target was not found
51
}
52
public void
output( )
53 {
54 Node position = head;
55
while
(position != null)
56 {
57 System.out.print(position.data.toString( ) + " ");
58 position = position.link;
59 }
60 System.out.println( );
61 }