HashSet的实例
1 import java.util.HashSet;
2 import java.util.Iterator;
3
4 public class HashSetDemo {
5
6 public static void main(String[] args) {
7 HashSet hs = new HashSet();
8 hs.add("heihei");
9 hs.add("hehe");
10 hs.add("hahha");
11 hs.add("xixi");
12 hs.add("hehe");
13 hs.add("hahha");
14 hs.add("xixi");
15
16 Iterator it = hs.iterator();
17
18 while (it.hasNext()) {
19 System.out.println(it.next());
20 }
21 }
22 }
结果:
从结果发现HashSet不会由值重复,那就要判断其元素是否相同
判断的原理:
判断两个元素的哈希值是否相同
如果哈希值相同就判断两个元素的内容是否相同
如果哈希值不同就不判断两个元素的内容
代码描述:就是判断HashSet中的元素的hashCode和equals方法。
HashSet元素为自定义类型,验证代码:
①、元素类型
1 public class Person {
2
3 private String name;
4 private int age;
5
6 public Person() {
7 super();
8 }
9
10 public Person(String name, int age) {
11 super();
12 this.name = name;
13 this.age = age;
14 }
15
16 public String getName() {
17 return name;
18 }
19
20 public void setName(String name) {
21 this.name = name;
22 }
23
24 public int getAge() {
25 return age;
26 }
27
28 public void setAge(int age) {
29 this.age = age;
30 }
31
32 @Override
33 public int hashCode() {
34 System.out.println(this + ":-------hashCode");
35 return this.name.hashCode() + this.age;
36 }
37
38 @Override
39 public boolean equals(Object obj) {
40 System.out.println(this + ":-------equals-------" + obj);
41 if (!(obj instanceof Person))
42 throw new ClassCastException("类型不对");
43 Person person = (Person) obj;
44 return this.name.equals(person.name) && person.age == this.age;
45 }
46
47 @Override
48 public String toString() {
49
50 return this.name + ":" + this.age;
51 }
52 }
②、HashSet存储
1 import java.util.HashSet;
2 import java.util.Iterator;
3
4 import cn.marw.common.bean.Person;
5
6 public class HashSetTest {
7
8 public static void main(String[] args) {
9 HashSet hs = new HashSet();
10
11 hs.add(new Person("wang1", 31));
12 hs.add(new Person("wang2", 32));
13 hs.add(new Person("wang3", 33));
14 hs.add(new Person("wang4", 34));
15 hs.add(new Person("wang2", 32));
16 Iterator it = hs.iterator();
17 while (it.hasNext()) {
18 Person p = (Person) it.next();
19 System.out.println(p.getName() + ":" + p.getAge());
20
21 }
22 }
23 }
結果:
总结:
HastSet判断集合元素是否相同,就是看元素的hashCode和equals方法
HastSet的方法contains和remove都要看元素的hashCode和equals方法