概念
Set接口继承Collection接口,用来包含一组无序无重复的对象,它的常用实现类有HashSet(内部对象是散列存取,采用哈希技术)、TreeSet(存储的数据是升序的)
下面以HashSet测试Set存储
Studnet.java
public class Student {
private String id;
private String name;
public Student(String id, String name) {
super();
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
System.out.println("true");
return true;
}
if ((obj == null) || (obj.getClass() != this.getClass())) {
System.out.println("false");
return false;
}
if (id == ((Student) obj).id && name == ((Student) obj).name) {
return true;
} else {
return false;
}
}
@Override
public int hashCode() {
int flag = 36;
int idNum = Integer.parseInt(id);
return flag * idNum;
}
}
HashSetTest.java
import java.util.HashSet;
import java.util.Set;
public class HashSetTest {
public static void main(String[] args) {
Student s1=new Student("1","li");
Student s2=new Student("2","ji");
Student s3=new Student("3","ji");
Student s4=new Student("3","ji");
Set<Student> hs=new HashSet<>();
hs.add(s1);
hs.add(s2);
hs.add(s3);
hs.add(s4);
for (Student student : hs) {
System.out.println(student.getId()+":"+student.getName());
}
}
}
运行结果: 1:li 2:ji 3:ji
分析
要使用Set存储Object的对象,执行add方法的时候,会先判断equals方法是否与已有的值相等,再判断是否有相同的hash值,若这两个方法结果都为true,则这个对象就认为已经存在,不插入,所以,我们要对equals和hashCode方法进行重写。
转载请注明原文地址: https://ju.6miu.com/read-1424.html