Java中的自然排序
自然排序
定制排序
自然排序
TreeSet集合在存储数据时有一定的顺序,它会将一些数据进行比较,比较调用的是comparaTo()方法,该方法是在Comparable中定义的,自然排序要求TreeSet集合中存储的数据必须实现Comparable接口,并且重写ComparaTo()方法
public class 自然排序 {
public static void main(String[] args) {
//定义一个TreeSet集合
TreeSet treeSet = new TreeSet();
Teacher t1 = new Teacher(“Jack”,19);
Teacher t2 = new Teacher(“King”,20);
Teacher t3 = new Teacher(“Tom”,19);
Teacher t4 = new Teacher(“Rose”,20);
treeSet.add(t1);
treeSet.add(t2);
treeSet.add(t3);
treeSet.add(t4);
System.out.println(treeSet);
}
}
//定义Teacher类实现Comparable接口
class Teacher implements Comparable{
String name;
int age;
public Teacher(String name,int age){
this.name = name;
this.age = age;
}
//重写toString方法
@Override
public String toString() {
return "Teacher{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
//先比较年龄在比较名字
@Override
public int compareTo(Object o) {
Teacher teacher = (Teacher)o;
if (this.age > teacher.age){
return 1;
}
if (this.age == teacher.age){
return this.name.compareTo(teacher.name);
}
return -1;
}
}
运行结果
[Teacher{name=‘Jack’, age=19}, Teacher{name=‘Tom’, age=19}, Teacher{name=‘King’, age=20}, Teacher{name=‘Rose’, age=20}]
1
定制排序
如果单单使用ComparaTo()不能满足要求,这时可以通过在创建TreeSet集合的时候就自定义一个比较器来对元素进行定制排序
import java.util.Comparator;
import java.util.TreeSet;
public class 定制排序 {
public static void main(String[] args) {
//在创建集合是传入比较器
TreeSet treeSet = new TreeSet(new MyComparable());
treeSet.add(“Jack”);
treeSet.add(“Tom”);
treeSet.add(“Helena”);
System.out.println(treeSet);
}
}
//自定义的比较器
class MyComparable implements Comparator{
@Override
public int compare(Object o1, Object o2) {
//以单词的长度来排序
String s1 = (String)o1;
String s2 = (String)o2;
int resoult = s1.length() - s2.length();
return resoult;
}
}
结果
[Tom, Jack, Helena]