1、Comparable用法
Comparable指的是可比较的,使用方法是首先让待排序的类实现Comparable接口,并重写compareTo方法,然后调用Arrays.sort对目标对象进行排序。
public class UserBean implements Comparable<UserBean> {
private String id;
private String username;
private String age;
// 省略了 set and get
public int compareTo(UserBean o) {
if(this.age > o.getAge()){
return 1;
}else if(this.age < o.getAge()){
return -1
}else{
return 0;
}
}
}
UserBean[] array = UserBean[3];
array[0] = new UserBean("1","zhangsan","11");
array[1] = new UserBean("2","lisi","12");
array[2] = new UserBean("3","wangwu","13");
Arrays.sort(array);
2、Comparator
实现comparator接口,将Comparator中的compare()方法进行重写,然后将comparator对象传入到arrays.sort()方法中
package edu.sjtu.ist.comutil;
import java.util.Comparator;
class Student {
private String name;
private int age;
private float score;
public Student(String name, int age, float score) {
this.name = name;
this.age = age;
this.score = score;
}
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 float getScore() {
return score;
}
public void setScore(float score) {
this.score = score;
}
public String toString()
{
return name+"\t\t"+age+"\t\t"+score;
}
}
class StudentComparator implements Comparator<Student>{
@Override
public int compare(Student o1, Student o2) {
// TODO Auto-generated method stub
if(o1.getScore()>o2.getScore())
return -1;
else if(o1.getScore()<o2.getScore())
return 1;
else{
if(o1.getAge()>o2.getAge())
return 1;
else if(o1.getAge()<o2.getAge())
return -1;
else
return 0;
}
}
}
public class ComparableDemo02 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Student stu[]={new Student("zhangsan",20,90.0f),
new Student("lisi",22,90.0f),
new Student("wangwu",20,99.0f),
new Student("sunliu",22,100.0f)};
java.util.Arrays.sort(stu,new StudentComparator());
for(Student s:stu)
{
System.out.println(s);
}
}
}