Set容器--HashSet集合
Set容器特点:
① Set容器是一个不包含重复元素的Collection,并且最多包含一个null元素,它和List容器相反,Set容器不能保证其元素的顺序;
② 最常用的两个Set接口的实现类是HashSet和TreeSet;
1 HashSet<String> data=new HashSet<String>();
2 data.add("张三");
3 data.add("李四");
4 data.add("jay");
5 data.add("jack");
6 data.add("jay");
7 System.out.println(data);
输出结果:
[张三,李四,jay,jack]
此处第二个jay没有存入;可以将其打印出来System.out.println(data.add("jay"));,结果显示第一个为true,第二个为false
编写一个Student类:
1 class Student{
2 private String name;
3 private int age;
4 public Student(String name, int age) {
5 super();
6 this.name = name;
7 this.age = age;
8 }
9 public String getName() {
10 return name;
11 }
12 public void setName(String name) {
13 this.name = name;
14 }
15 public int getAge() {
16 return age;
17 }
18 public void setAge(int age) {
19 this.age = age;
20 }
21 }
主方法中添加及输出
1 HashSet<Student> stuSet=new HashSet<Student>();
2 System.out.println(stuSet.add(new Student("张三",20)));
3 System.out.println(stuSet.add(new Student("李四",30)));
4 System.out.println(stuSet.add(new Student("张三",20)));
5 System.out.println(stuSet.size());
6
输出结果:
true
true
true
3
由此可见:new Student("张三",20)两次都创建了,若想字相同时只创建一次则需重构hashCode和equals方法
如下:
1 @Override
2 public int hashCode() {
3 final int prime = 31;
4 int result = 1;
5 result = prime * result + age;
6 result = prime * result + ((name == null) ? 0 : name.hashCode());
7 return result;
8 }
9 @Override
10 public boolean equals(Object obj) {
11 if (this == obj)
12 return true;
13 if (obj == null)
14 return false;
15 if (getClass() != obj.getClass())
16 return false;
17 Student other = (Student) obj;
18 if (age != other.age)
19 return false;
20 if (name == null) {
21 if (other.name != null)
22 return false;
23 } else if (!name.equals(other.name))
24 return false;
25 return true;
26 }
再次执行,输出结果:
true
true
false
2
总结:HashSet的内部操作的底层数据是HashMap,只是我们操作的是HashMap的key;