在集合或者数组中,有时候需要对里面的元素,也就是对象进行排序,依照对象的某个或者某几个属性从大到小或者从小到大进行排序,我们可以采用直接编码的方式,将集合或者数组中的元素进行重新排列,但,采用java本身提供的接口,无疑是一种更有效的方法。
java提供两种方式来提供比较功能。第一种是实现java.lang.Comparable接口,它有一个 int compareTo(Object o)方法,重写此方法即可。
package compare;
public class People implements Comparable {
private int id;
private String name;
public People(int id,String name){
this.id=id;
this.name=name;
}
/*
* 这里表示按id从小到大排序,如果该对象小于、等于或大于指定对象Object o,则分别返回负整数、零或正整数
* 如果需要从大到小排序,则如果该对象小于、等于或大于指定对象Object o,则分别返回正整数、零或负整数
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
public int compareTo(Object o) {
People people=(People)o;
if(id<people.getId()){
return -1;
}
if(id>people.getId()){
return 1;
}
return 0;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
测试代码如下:
List peopleList = new ArrayList();
peopleList.add(new People(2, "张三"));
peopleList.add(new People(1, "李四"));
peopleList.add(new People(0, "王五"));
System.out.println("排序前");
for (int i = 0; i < peopleList.size(); i++) {
People people = (People) peopleList.get(i);
System.out.println(people.getId() + " " + people.getName());
}
Collections.sort(peopleList);
System.out.println("排序后");
for (int i = 0; i < peopleList.size(); i++) {
People people = (People) peopleList.get(i);
System.out.println(people.getId() + " " + people.getName());
}
以下是输出结果:
排序前
2 张三
1 李四
0 王五
排序后
0 王五
1 李四
2 张三
另一种方式是实现java.util.Comparator接口,重写int compare(Object o1, Object o2)方法即可。
package compare;
import java.util.Comparator;
public class Compare implements Comparator {
/*
* 这里表示按id从小到大排序,如果该对象o1小于、等于或大于指定对象o2,则分别返回负整数、零或正整数
* 如果需要从大到小排序,则如果对象o1小于、等于或大于指定对象o2,则分别返回正整数、零或负整数
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
*/
public int compare(Object o1, Object o2) {
Student s1=(Student)o1;
Student s2=(Student)o2;
if(s1.getId()<s2.getId()){
return -1;
}
if(s1.getId()>s2.getId()){
return 1;
}
return 0;
}
}
Student类代码如下:
package compare;
public class Student {
private int id;
private String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
测试代码如下:
List<Student> list = new ArrayList<Student>();
Student s1 = new Student(1, "a");
Student s2 = new Student(2, "b");
Student s3 = new Student(3, "c");
list.add(s3);
list.add(s2);
list.add(s1);
System.out.println("排序前");
for (int i = 0; i < list.size(); i++) {
Student s = list.get(i);
System.out.println(s.getId() + " " + s.getName());
}
Collections.sort(list, new Compare());
System.out.println("排序后");
for (int i = 0; i < list.size(); i++) {
Student s = list.get(i);
System.out.println(s.getId() + " " + s.getName());
}
结果如下:
排序前
3 c
2 b
1 a
排序后
1 a
2 b
3 c
结果和预期是相同的。
这两种方法都可以实现按照对象的属性进行排序,或者自己定义排序规则,不过个人更倾向于使用第二种方式,因为这种方式对JavaBean不进行任何的修改,而且扩展起来也很方便