在实际的项目中,经常会遇到排序问题,对于基本数据类型java支持Arrays.sort()和Collection.sort()对集合进行排序,但是对用户自定义类型排序呢?java给我们提供了两种解决方案。
一:通过实现Comparable<Object> 在内部实现
示例代码:
package com.lky.model; import java.io.Serializable; @SuppressWarnings("serial")
public class Student implements Serializable, Comparable<Student> { private String name;
private Integer id;
private String log; public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getLog() {
return log;
} public void setLog(String log) {
this.log = log;
} @Override
public String toString() {
return "Student [name=" + name + ", id=" + id + ", log=" + log + "]";
} @Override
public int compareTo(Student o) {
return o.getId()-id;
} }
二.通过实现 Comparator<Object> 来定义排序规则
示例代码:
package com.lky.test; import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Random; import org.junit.Test; import com.lky.model.Student; public class compartorTest { public class OutComparator implements Comparator<Student> { @Override
public int compare(Student o1, Student o2) {
int result = 0;
result = o1.getId() - o2.getId(); if (result == 0) {
return o1.getName().compareTo(o2.getName());
} else {
return result;
}
}
} @Test
public void test() {
List<Student> array = new ArrayList<Student>();
for (int i = 0; i < 20; ++i) {
Student student = new Student();
student.setId(new Random().nextInt(10) + 1);
student.setLog("log" + i);
student.setName("lky" + i);
array.add(student);
}
Collections.sort(array);// 采用默认排序
// Collections.sort(array, new OutComparator());//采用自定义排序
for (Student student : array) {
System.out.println(student);
}
} }