实现自定义的排序常用有两种方法
一、实体类 实现java.lang.Comparable接口且重写compareTo()方法
二、业务排序类 实现java.util.Compartor接口且重写compare()方法
第一种方法举例:
实体类为学生类 属性有学分,学号,姓名,该类实现了Comparable接口并重写compareTo()方法 本例按照学分降序排列
public class Student implements Comparable
private int id;
private int score;
private String name;
public int getId() {
return id;
}
public int getScore() {
return score;
}
public Student(int id, int score, String name) {
super();
this.id = id;
this.score = score;
this.name = name;
}
@Override
public String toString(){
return " 学号:"+id+" 姓名:"+name+" 学分:"+score;
}
@Override
public int compareTo(Student o) {
// TODO Auto-generated method stub
if(this.getScore()>o.getScore())
return -1;
else if(this.getScore()
else {
if(this.getId()>o.getId())
return -1;
else if(this.getId()>o.getId())
return 1;
else return 0;
}
}
}
接下来建立TreeSet类将实例化学生对象添加到集合
import java.util.TreeSet;
public class MyTree2 {
public static void main(String[] args) {
TreeSet
t.add( new Student(1000,33,"java1"));
t.add( new Student(1001,340,"java2"));
t.add( new Student(1002,200,"java3"));
//遍历集合输出
t.forEach((Student o) -> {
System.out.println(o);
});
}
}
运行结果
如果没有在Student类中实现该接口将会抛异常
第二种方法举例
实体类不再实现接口,在业务排序类实现不同的排序需求
实体类:
public class Student {
private int id;
private int score;
private String name;
public int getId() {
return id;
}
public int getScore() {
return score;
}
public Student(int id, int score, String name) {
super();
this.id = id;
this.score = score;
this.name = name;
}
@Override
public String toString(){
return " 学号:"+id+" 姓名:"+name+" 学分:"+score;
}
}
排序类(按id排序):
import java.util.Comparator;
public class SortId implements Comparator
@Override
public int compare(Student ob1, Student ob2) {
// TODO Auto-generated method stub
if(ob1.getId()>ob2.getId()) {
return 1;
}else if(ob1.getId()
}
else {
if(ob1.getScore()>ob2.getScore()) {
return 1;
}else if(ob1.getScore()
}
else return 0;
}
}
}
排序类(按学分排序):
import java.util.Comparator;
public class SortScore implements Comparator{
@Override
public int compare(Object o1, Object o2) {
// TODO Auto-generated method stub
Student ob1=(Student)o1;
Student ob2=(Student)o2;
if(ob1.getScore()>ob2.getScore()) {
return 1;
}else if(ob1.getScore()
}
else {
if(ob1.getId()>ob2.getId()) {
return 1;
}else if(ob1.getId()
}
else return 0;
}
}
}
同样建立TreeSet类将实例化学生对象添加到集合
import java.util.TreeSet;
public class MyTree1 {
public static void main(String[] args) {
SortScore c =new SortScore();
SortId c1 = new SortId();
//在new TreeSet对象是指定不同的排序
TreeSet
TreeSet
t.add( new Student(1003,33,"java1"));
t.add( new Student(1002,34,"java2"));
t.add( new Student(1001,2,"java3"));
t1.add( new Student(1003,33,"java1"));
t1.add( new Student(1002,34,"java2"));
t1.add( new Student(1001,2,"java3"));
System.out.println("-------按学分排序---------");
t.forEach((Student o) -> {
System.out.println(o);
});
System.out.println("-------按id排序---------");
t1.forEach((Student o) -> {
System.out.println(o);
});
}
}
总结
两种方法均可以实现排序,第二种方法在排序方式多种的情况下更实用