我们知道,set通常被用于list的去重处理,例如:
List<String> list = new ArrayList<>();
list.add("小明");
list.add("小花");
list.add("小绿");
list.add("小明");
System.out.println(list);
System.out.println("------");
Set<String> set = new HashSet<>(list);
System.out.println("去重后的结果:"+set);
但如果遇到对象去重,我们发现无法去重
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class Main {
public static void main(String[] args) {
List<Main.Student> list = new ArrayList<>();
list.add(new Student("小花",12));
list.add(new Student("小绿",12));
list.add(new Student("小红",12));
list.add(new Student("小花",12));
System.out.println(list);
System.out.println("------");
Set<Main.Student> set = new HashSet<>(list);
System.out.println("去重后的结果:"+set);
}
static class Student{
private String name;
private Integer age;
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Student(String name, Integer age) {
this.name = name;
this.age = age;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
}
可以发现红圈中的小花并没有被去重
set方法去重的原理是依赖于map
而map中的key防重复的方法是使用我们的equals方法
我们知道equals方法比较的是内存的地址
当我们创建对象的时候,将会开辟一个新的地址
即使里面的内容相同,地址不同,也是两个不相同的对象
重写equals方法,将地址比较重写为里面的属性比较
Student类中加上
@Override
public boolean equals(Object obj) {
if (obj instanceof Main.Student){
return name.equals(((Student) obj).getName())&&age.equals(((Student) obj).getAge());
}else {
return false;
}
}
最后我们测试equals方法
System.out.println(new Student("小花", 12).equals(new Student("小花", 12)));
返回为true
但我们发现依旧无法去重
还需要重写hashCode方法
@Override
public int hashCode() {
return name.hashCode();
}
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class Main {
public static void main(String[] args) {
List<Main.Student> list = new ArrayList<>();
list.add(new Student("小花",12));
list.add(new Student("小绿",12));
list.add(new Student("小红",12));
list.add(new Student("小花",12));
System.out.println(list);
System.out.println("------");
Set<Main.Student> set = new HashSet<>(list);
System.out.println("去重后的结果:"+set);
System.out.println(new Student("小花", 12).equals(new Student("小花", 12)));
}
static class Student{
private String name;
private Integer age;
@Override
public int hashCode() {
return name.hashCode();
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Main.Student){
return name.equals(((Student) obj).getName())&&age.equals(((Student) obj).getAge());
}else {
return false;
}
}
public Student(String name, Integer age) {
this.name = name;
this.age = age;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
}