[size=large][color=red]要对List排序,你要对List里装的这种类型的类实现排序接口(Comparable).
举个例子:
下面这个例子是对List进行排序.使用Collections.sort(List list);方法,此方法会调用MyObject的compareTo方法.所以在MyObject类定义里要实现compareTo方法.
Java代码
public class ListSort {
/**
* main()
* 2010-4-2,下午09:25:57
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
List lists = new ArrayList();
MyObject obj1 = new MyObject("d");
MyObject obj2 = new MyObject("a");
lists.add(obj1);
lists.add(obj2);
Collections.sort(lists);
for (MyObject myObject : lists) {
System.out.println(myObject.getContent());
}
}
}
class MyObject implements Comparable{
private String content;
public MyObject(String _content) {
this.content = _content;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public int compareTo(MyObject obj) {
// TODO Auto-generated method stub
if (null == obj) return 1;
else {
return this.content.compareTo(obj.content);
}
}
}
下面是Collections.sort方法
Java代码
public static > void sort(List list) {
Object[] a = list.toArray();
Arrays.sort(a);
ListIterator i = list.listIterator();
for (int j=0; j
i.next();
i.set((T)a[j]);
}
}
实际上我们的MyObject类的方法compareTo是在Arrays.sort()中被调用的...
请看..
Java代码
public static void sort(Object[] a) {
Object[] aux = (Object[])a.clone();
mergeSort(aux, a, 0, a.length, 0);
}
Java代码
private static void mergeSort(Object[] src,
Object[] dest,
int low,
int high,
int off) {
int length = high - low;
// Insertion sort on smallest arrays
if (length < INSERTIONSORT_THRESHOLD) {
for (int i=low; i
for (int j=i; j>low &&
((Comparable) dest[j-1]).compareTo(dest[j])>0; j--)
swap(dest, j, j-1);
return;
}
// Recursively sort halves of dest into src
int destLow = low;
int destHigh = high;
low += off;
high += off;
int mid = (low + high) >> 1;
mergeSort(dest, src, low, mid, -off);
mergeSort(dest, src, mid, high, -off);
// If list is already sorted, just copy from src to dest. This is an
// optimization that results in faster sorts for nearly ordered lists.
if (((Comparable)src[mid-1]).compareTo(src[mid]) <= 0) {
System.arraycopy(src, low, dest, destLow, length);
return;
}
// Merge sorted halves (now in src) into dest
for(int i = destLow, p = low, q = mid; i < destHigh; i++) {
if (q >= high || p < mid && ((Comparable)src[p]).compareTo(src[q])<=0)
dest[i] = src[p++];
else
dest[i] = src[q++];
}
}
[/color][/size]
当然,这是一种实现排序的办法.还有一种是实现Comparator,实现这个接口,然后使用
Collections.sort(List list,Comparator c);这个方法来排序..
标签:list