HashSet、LinkedHashSet以及TreeSet
HashSet与LinkedHasgSet在存储自定义对象时,该类需要重写HashCode()与equals()方法
若不重写上述方法,会造成存储元素不唯一。
public class Student {
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return age == student.age && Objects.equals(name, student.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
TreeSet在存储自定义对象时,当使用内部比较器时,该类需重写Comparable接口中compareTo()方法,当使用外部比较器时,该类需重写Comparator接口中compare()方法。
若不重写以上方法,会直接报错。
内部比较器
@Override
public int compareTo(Student o) {
return this.age-o.age;
}
外部比较器
public class StuNameCompare implements Comparator<Student> {
@Override
public int compare(Student stu1, Student stu2) {
return stu1.getName().compareTo(stu2.getName());
}
}
//在主函数中的实现与应用
Comparator<Student> comp=new StuNameCompare();
Set<Student> set2=new TreeSet<>(comp);
通过匿名内部类实现
```java
Comparator<Student> comp1=new Comparator<Student>(){
@Override
public int compare(Student stu1, Student stu2) {
if (stu1.getAge()>stu2.getAge())
return 1;
if (stu1.getAge()<stu2.getAge())
return -1;
else
return stu1.getName().compareTo(stu2.getName());
}
};
Set<Student> set3=new TreeSet<>(comp1);
若有错误,请留言!!!