TreeSet自定义类存储(使用比较器)
往TreeSet添加元素的时候,如果元素本身没有具备自然顺序的特性,而元素所属的类也没有实现comparable接口那么必须在创建TreeSet的时候传入一个比较器。
如何自定义比较器:自定义一个类实现comparator接口即可,把元素与元素之间的比较规则定义在compare方法内即可
自定义比较器的格式:
class 类名 implements Comparator {
}
实例:
首先定义一个员工类
package com.zzu.java13.treeset;
public class Employment {
String name;
int age ;
double salary;
public Employment(String name, int age, double salary) {
super();
this.name = name;
this.age = age;
this.salary = salary;
}
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;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
@Override
public String toString() {
return "Employment [name=" + name + ", age=" + age + ", salary=" + salary + "]";
}
}
然后自定义一个比较器
package com.zzu.java13.treeset;
import java.util.Comparator;
public class EmpComparator implements Comparator {
@Override
public int compare(Object o1, Object o2) {
Employment e1 = (Employment) o1;
Employment e2 = (Employment) o2;
return e1.age-e2.age;
}
}
创建一个treeset类
package com.zzu.java13.treeset;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;
public class EmpTreeset {
public static void main(String[] args) {
//创建一个比较器对象
EmpComparator comparator = new EmpComparator();
//创建treeset的时候传入比较器
Set<Employment> set = new TreeSet<Employment>(comparator);
set.add(new Employment("张三",39,3000));
set.add(new Employment("李四",45,3000));
set.add(new Employment("王五",34,3000));
set.add(new Employment("赵六",23,3000));
Iterator it = set.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
}
输出结果为:
Employment [name=赵六, age=23, salary=3000.0]
Employment [name=王五, age=34, salary=3000.0]
Employment [name=张三, age=39, salary=3000.0]
Employment [name=李四, age=45, salary=3000.0]