1,构造方法:
TreeSet(Comparator super E> comparator)
构造一个新的空 TreeSet,它根据指定比较器进行排序。 自定义排序
2,Comparator 接口:
int compare(T o1, T o2) 比较用来排序的两个参数。
boolean equals(Object obj) 指示某个其他对象是否“等于”此 Comparator
3,实例:
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
import java.util.Comparator;
public class MyComparator implements Comparator {
@Override
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
}
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
import java.util.Comparator;
public class StuComparator implements Comparator{
@Override
public int compare(Stu o1, Stu o2) {
int num=o1.getName().compareTo(o2.getName());
return num!=0?num:(o1.getAge()
}
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
public class Stu {
private String name;
private int age;
public Stu() {
}
public Stu(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 instanceof Stu)) return false;
Stu stu = (Stu) o;
if (getAge() != stu.getAge()) return false;
return getName().equals(stu.getName());
}
@Override
public int hashCode() {
int result = getName().hashCode();
result = 31 * result + getAge();
return result;
}
@Override
public String toString() {
return "Stu{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
import java.util.TreeSet;
public class TreeSetDemo2 {
public static void main(String[] args){
//根据TreeSet的某个构造方法TreeSet(Comparator super E> comparator)
// 构造一个新的空的TreeSet,根据制定比较器进行排序
MyComparator myComparator=new MyComparator();
TreeSet test=new TreeSet(myComparator);
test.add(“susan”);
test.add(“peter”);
test.add(“jerry”);
test.add(“jerry”);//重复的元素不出现
for(String item:test){
System.out.println(“集合元素:”+item);
}
System.out.println("=自定义类型===");
StuComparator stuComparator=new StuComparator();
TreeSet test2=new TreeSet(stuComparator);
Stu stu1=new Stu(“jerry”,20);
Stu stu2=new Stu(“susan”,19);
Stu stu3=new Stu(“peter”,18);
Stu stu4=new Stu(“jerry”,18);
test2.add(stu1);
test2.add(stu2);
test2.add(stu3);
test2.add(stu4);
for(Stu s:test2){
System.out.println(“集合元素:”+s);
}
}
}