|
| |
"Java Collections"
Vol. 9, Issue 2, p. 40
Listing 1: Person Class
1 // Person Class
2 public class Person {
3 private String ssn;
4
5 public Person(String newSSN) {
6 this.ssn = newSSN;
7 }
8
9 public String toString() {
10 return ssn;
11 }
12 }
Listing 2: PedanticPerson
1 // PedanticPerson Class overrides
2 // hashCode and equals.
3 public class PedanticPerson
4 extends Person {
5
6 public PedanticPerson(
7 String newSSN) {
8 super(newSSN);
9 }
10 public int hashCode() {
11 return getSSN().hashCode();
12 }
13 public boolean equals(
14 Object obj) {
15 Person p = (Person) obj;
16
17 return getSSN().equals(
18 p.getSSN());
19 }
20 }
Listing 3: Main Program
1 import java.util.HashSet;
2 import java.util.Set;
3
4 public class HashSetExample {
5
6 public static void main(
7 String[] args) {
8
9 Set dupSet = new HashSet();
10 dupSet.add(new
11 Person("000-11-1111"));
12 dupSet.add(new
13 Person("222-23-1234"));
14 dupSet.add(new
15 Person("000-11-1111"));
16
17 // has duplicates
18 System.out.println(dupSet);
19 Set set = new HashSet();
20 set.add(new
21 PedanticPerson("000-11-1111"));
22 set.add(new
23 PedanticPerson("222-23-1234"));
24 set.add(new
25 PedanticPerson("000-11-1111"));
26
27 // has no duplicates
28 System.out.println(set);
29
30 }
31 }
Listing 4: PersonComparator
1 // PersonComparator will be used
2 // to sort the Persons in
3 // descending order based
4 // on SSN.
5 public class PersonComparator
6 implements Comparator {
7
8 public int compare(
9 Object o1,
10 Object o2) {
11
12 Person p1 = (Person) o1;
13 Person p2 = (Person) o2;
14
15 String ssn1 = p1.getSSN();
16 String ssn2 = p2.getSSN();
17
18 return ssn2.compareTo(ssn1);
19 }
20 }
|
|
All Rights Reserved
Copyright © 2004 SYS-CON Media, Inc.
E-mail: info@sys-con.com
Java and Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries. SYS-CON Publications, Inc. is independent of Sun Microsystems, Inc.
|