Remove duplicates using HashSet

Source: Internet
Author: User
1 package com. test;
2
3 public class Person {
4
5 private String id;
6 private String name;
7
8 public String getId (){
9 return id;
10}
11
12 public void setId (String id ){
13 this. id = id;
14}
15
16 public String getName (){
17 return name;
18}
19
20 public void setName (String name ){
21 this. name = name;
22}
23
24 @ Override
25 public int hashCode (){
26 int result;
27 result = (name = null? 0: name. hashCode ());
28 result = 37 * result + (id = null? 0: id. hashCode ());
29 return result;
30}
31
32 @ Override
33 public boolean equals (Object obj ){
34 if (this = obj ){
35 return true;
36}
37 if (! (Obj instanceof Person )){
38 return false;
39}
40 final Person other = (Person) obj;
41 if (this. id. equals (other. getId () & this. name. equals (other. getName ())){
42 return true;
43} else {
44 return false;
45}
46}
47
48}

 

 

 

 

1 package com. test;
2
3 import java. util. HashSet;
4 import java. util. Iterator;
5
6 public class HashSetTest {
7 public static void main (String [] args ){
8 Person person1 = new Person ();
9 Person person2 = new Person ();
10 Person person3 = new Person ();
11
12 person1.setId ("1 ");
13 person1.setName ("test1 ");
14 person2.setId ("1 ");
15 person2.setName ("test1 ");
16 person3.setId ("2 ");
17 person3.setName ("test1 ");
18
19 HashSet set = new HashSet ();
20 set. add (person1 );
21 set. add (person2 );
22 set. add (person3 );
23
24 System. out. println (set. size ());
25
26 Iterator iter = set. iterator ();
27 while (iter. hasNext ()){
28 Person temp = (Person) iter. next ();
29 System. out. println (temp. getId () + ":" + temp. getName ());
30}
31
32
33}
34}

 

 

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.