1 import org.junit.Test;
2
3 import java.util.HashSet;
4 import java.util.LinkedHashSet;
5 import java.util.Set;
6 import java.util.TreeSet;
7
8 public class TestSet {
9 /*
10 Collection接口:
11 |---Set接口:存储无序,不可重复的元素
12 1,HashSet
13 2,LinkedHashSet
14 3,TreeSet
15 Set的元素是如何保存的:使用了哈希算法
16 向Set中添加对象时:调用hashCode()方法,计算哈希值
17 hashCode()方法要与equals()方法一致
18
19 */
20 @Test
21 public void testTreeSet1(){
22 Set set =new TreeSet();
23
24 }
25 @Test
26 public void testLinkedHashSet(){
27 Set set =new LinkedHashSet();
28 set.add(123);
29 set.add("aaa");
30
31 }
32 @Test
33 public void testHashSet() {
34 //Set无序性:无序性!=随机性
35 //不可重复
36 Set set = new HashSet();
37 set.add(123);
38 set.add("abd");
39 Person p1 =new Person("noo",18);
40 Person p2 =new Person("noo",18);
41 System.out.println(p1.equals(p2));
42 System.out.println(p1.hashCode());
43 System.out.println(p2.hashCode());
44 System.out.println(set.size());
45 set.add(p1);
46 set.add(p2);
47 System.out.println(set);
48 }
49
50
51 }
1 public class Person {
2 private String name ;
3 private Integer age ;
4 public String getName(){
5 return name;
6 }
7 public Integer getAge(){
8 return age;
9 }
10 public void setName(){
11 this.name=name;
12 }
13 public void setAge(){
14 this.age=age;
15 }
16 public Person(String name,Integer age){
17 super();
18 this.age=age;
19 this.name=name;
20 }
21 public Person(){
22 super();
23 }
24 @Override
25 public String toString(){
26 return "Person[name="+name+",age="+age+"]";
27 }
28 }