Java Reference
In-Depth Information
It is important to note that if you intend to use the
HashSet<T>
class with your own
class as the parameterized type
T
, then your class must override the following methods:
public int
hashCode();
public boolean
equals(Object obj);
The
hashCode()
method should return a numeric key that is ideally a unique
identifier for an object in your class. See Section 15.5 for a discussion about hash codes.
It is always a good idea to override the
equals()
method for any class you write, but
you must override it in this scenario. Java will use the hash code to index the object and
then use the
equals()
method to check if an object exists in the set. If the hash code
for two different objects is identical, the objects will still be indexed correctly as long
as
equals()
indicates they are unique. However, the identical hash codes will cause a
collision that will decrease performance.
Display 16.6 shows a sample program that uses the
HashSet<T>
class. This
program is conceptually similar to the program in Display 15.38, in which sets
containing strings of round things and green things were manipulated in various
Display 16.6
HashSet<T>
Class Demo
(part 1 of 3)
1
import
java.util.HashSet;
2
import
java.util.Iterator;
3
public class
HashSetDemo
4 {
5
private static void
outputSet(HashSet<String> set)
6 {
7 Iterator<String> i = set.iterator();
8
while
(i.hasNext())
9 System.out.print(i.next() + " ");
10 System.out.println();
11
The
outputSet
method uses an iterator
to print the contents of
a
HashSet<T>
object.
Iterators are described
in Section 16.3.
}
12
public static void
main(String[] args)
13 {
14 HashSet<String> round =
new
HashSet<String>();
15 HashSet<String> green =
new
HashSet<String>();
16
// Add some data to each set
17 round.add("peas");
18 round.add("ball");
19 round.add("pie");
20 round.add("grapes");
21 green.add("peas");
22 green.add("grapes");
23 green.add("garden hose");
24 green.add("grass");