Java Reference
In-Depth Information
1
/**
2
* Test program for HashSet.
3
*/
4
class IteratorTest
5
{
6
public static void main( String [ ] args )
7
{
8
List<SimpleStudent> stud1 = new ArrayList<SimpleStudent>( );
9
stud1.add( new SimpleStudent( "Bob", 0 ) );
10
stud1.add( new SimpleStudent( "Joe", 1 ) );
11
stud1.add( new SimpleStudent( "Bob", 2 ) ); // duplicate
12
13
// Will only have 2 items, if hashCode is
14
// implemented. Otherwise will have 3 because
15
// duplicate will not be detected.
16
Set<SimpleStudent> stud2 = new HashSet<SimpleStudent>( stud1 );
17
18
printCollection( stud1 ); // Bob Joe Bob (unspecified order)
19
printCollection( stud2 ); // Two items in unspecified order
20
}
21
}
22
23
/**
24
* Illustrates use of hashCode/equals for a user-defined class.
25
* Students are ordered on basis of name only.
26
*/
27
class SimpleStudent implements Comparable<SimpleStudent>
28
{
29
String name;
30
int id;
31
32
public SimpleStudent( String n, int i )
33
{ name = n; id = i; }
34
35
public String toString( )
36
{ return name + " " + id; }
37
38
public boolean equals( Object rhs )
39
{
40
if( rhs == null || getClass( ) != rhs.getClass( ) )
41
return false;
42
43
SimpleStudent other = (SimpleStudent) rhs;
44
return name.equals( other.name );
45
}
46
47
public int hashCode( )
48
{ return name.hashCode( ); }
49
}
figure 6.35
Illustrates the
equals
and
hashCode
methods for use in
HashSet
Search WWH ::
Custom Search