1. 自定义SortUtil类
import java.util.Comparator;
import java.util.List;
public class SortUtil {
/**
* List容器泛型比较器, 升序排序
* @param array
*/
public static <T extends Comparable<T>> void sort(List<T> list) {
sort(list, null);
}
/**
* List容器泛型比较器, 带业务排序功能, 升序排序
* @param array
*/
@SuppressWarnings({ "unchecked" })
public static <T> void sort(List<T> list, Comparator<T> c){
Object[] array = list.toArray();
int length = array.length;
boolean sorted;
// 趟数
for(int i = 0; i < length - 1; i++) {
sorted = true;
// 次数
for(int j = 0; j < length - i - 1; j++) {
if((c != null && ((Comparator<Object>)c).compare(array[j], array[j + 1]) > 0) || (c == null && ((Comparable<Object>)array[j]).compareTo(array[j + 1]) > 0)) {
Object temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
sorted = false;
}
}
if(sorted) { // 减少趟数
break;
}
}
for(int i = 0; i < array.length; i++) {
list.set(i, (T)array[i]);
}
}
/**
* 数组泛型比较器, 升序排序
* @param array
*/
public static <T extends Comparable<T>> void sort(T[] array) {
sort(array, null);
}
/**
* 数组泛型比较器, 带业务排序功能, 升序排序
* @param array
*/
@SuppressWarnings("unchecked")
public static <T> void sort(T[] array, Comparator<T> c) {
int length = array.length;
boolean sorted;
// 趟数
for(int i = 0; i < length - 1; i++) {
sorted = true;
// 次数
for(int j = 0 ; j < length - i - 1; j++) {
if((c != null && (c.compare(array[j], array[j + 1]) > 0)) || (c == null && ((Comparable<T>)array[j]).compareTo(array[j + 1]) > 0)) {
T temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
sorted = false;
}
}
if(sorted) { // 减少趟数
break;
}
}
}
}
2. 使用SortUtil类
import java.util.Comparator;
import java.util.Date;
public class UseMySortUtil {
public static void main(String[] args) {
}
}
/**
* 实现Comparator接口的,新闻条目安时间排序的业务类
*/
class NewsTime implements Comparator<NewItem>{
public int compare(NewItem o1, NewItem o2) {
return o2.time.compareTo(o1.time);
}
}
/**
* 实现Comparable接口的新闻类
*/
class NewItem implements Comparable<NewItem>{
public String title;
public int hits;
public Date time;
public NewItem(String title, int hits, Date time) {
this.title = title;
this.hits = hits;
this.time = time;
}
public int compareTo(NewItem o) {
int result = 0;
// 时间倒序
if((result = o.time.compareTo(time)) == 0) {
// 点击次数倒序
if((result = (o.hits - hits)) ==0) {
// 标题正序
result = title.compareTo(o.title);
}
}
return result;
}
public String toString() {
return "[title = " + title + " hits = " + hits + " time = " + time + "]";
}
}