要實(shí)現(xiàn)排序功能,一般有兩種途徑,這里對基本類型不適用,基本類型一般有Arrays中的靜態(tài)方法.
1.對象本身實(shí)現(xiàn)Comparable接口,那么該類的實(shí)例就是可以排序的.
有關(guān)Comparable: http://blog.csdn.net/treeroot/archive/2004/09/09/99613.aspx
只要實(shí)現(xiàn)了Comparable接口,就可以調(diào)用Collections的sort方法對集合中的元素排序.
2.指定一個Comparator,也就是實(shí)現(xiàn)了Comparator的類的一個實(shí)例.
但是Java本身只提供了一個Comparator的實(shí)現(xiàn),就是Collections.reverseOrder().
該方法返回的是一個已經(jīng)實(shí)現(xiàn)了Comparable接口的反序.
看一下Comparator的全部內(nèi)容:
public interface Comparator {
int compare(Object o1, Object o2);
boolean equals(Object obj);
}
定義了兩個方法,其實(shí)我們一般都只需要實(shí)現(xiàn)compare方法就行了,因?yàn)轭惗际悄J(rèn)從Object繼承
所以會使用Object的equals方法.
Comparator一般都作為一個匿名類出現(xiàn),對于沒有實(shí)現(xiàn)Comparable的對象的集合,排序的時候
需要指定一個Comparator.
這里舉例說明
對于實(shí)現(xiàn)了Comparable的類我們就用最簡單的Integer
List list=new ArrayList();
list.add(new Integer(3));
list.add(new Integer(53));
list.add(new Integer(34));
Collections.sort(list);
對于沒有實(shí)現(xiàn)Comparable的,我們就用Object,按照hashCode大小來排序.
List list= new ArrayList();
list.add(new Object());
list.add(new Object());
list.add(new Object());
Collections.sort(list,new Comparator(){ public int compare(Object o1, Object o2){
return (o1.hashCode()-o2.hashCode());}});
對集合排序的例子
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/*
* 當(dāng)前文件: TestCollections.java
* 創(chuàng)建日期: 2006-6-29
* 版 本 號: 1.0
* 作 者: Stevie Liu
*
*/
/**
* 親愛的kang1,請您在此詳細(xì)描述我的用途.
*/
class BookType{
String idsn;
String name;
/**
* @param idsn
* @param name
*/
public BookType(String idsn, String name)
{
super();
this.idsn = idsn;
this.name = name;
}
/**
* @return Returns the idsn.
*/
public String getIdsn()
{
return idsn;
}
/**
* @param idsn The idsn to set.
*/
public void setIdsn(String idsn)
{
this.idsn = idsn;
}
/**
* @return Returns the name.
*/
public String getName()
{
return name;
}
/**
* @param name The name to set.
*/
public void setName(String name)
{
this.name = name;
}
}
public class TestCollections
{
public static void main(String[] args)
{
List list=new ArrayList();
list.add(new BookType("1","k"));
list.add(new BookType("5","z"));
list.add(new BookType("4","g"));
Comparator OrderIsdn = new Comparator(){
public int compare(Object o1, Object o2){
BookType b1=(BookType)o1;
BookType b2=(BookType)o2;
return (b1.getIdsn().hashCode()-b2.getIdsn().hashCode());
}
};
Comparator OrderName = new Comparator(){
public int compare(Object o1, Object o2){
BookType b1=(BookType)o1;
BookType b2=(BookType)o2;
return (b1.getName().hashCode()-b2.getName().hashCode());
}
};
Collections.sort(list,OrderName);
Collections.reverse(list);
for(int i=0;i
BookType ss=(BookType)list.get(i);
System.out.print(ss.getIdsn());
System.out.println(ss.getName());
}
}
}