java 集合类的排序主要是用Collections.sort方法,Collections和Collection是不一样的,前者是类,后者是接口,我主要是想说明它的sort方法的几种类型,提示:实现接口的方法时,只需要比较两个数,大的返回1,相等返回0,小于返回-1。简单的说就是在方法里这样写:s1.num>s2.num?1:(s1.num==s2.num?0:-1);还要注意一点,在java中字符串比较是要用compareTo()方法来做比较的,方法就直接返回0或1或-1。
1.Collections.sort(List arg0);
这种是最简单的一种排序方法,只需要在List中存放的类中实现Comparable 接口及实现public int compareTo(Object arg0)方法即可。
2.Collections.sort(List arg0,Comparator arg1);
这种加入了比较器,具有更大的灵活性,便于管理,比较器可作为内部静态类的,以便于管理。比较器必须实现Comparator接口,具体可参照下列代码:
import java.util.Comparator;
public class Infoma {
private String ip;
private Integer port;
public Infoma(int port,String ip){
this.ip=ip;
this.port=port;
}
public static class SrcIpComparator implements Comparator{
public int compare(Object obj1,Object obj2){
CurrentFlow curFlow1=(CurrentFlow)obj1;
CurrentFlow curFlow2=(CurrentFlow)obj2;
int result=curFlow1.streamSrcIp.compareTo(curFlow2.streamSrcIp);
if(result==0){
result=curFlow1.streamSrcPort.compareTo(curFlow2.streamSrcPort);
}
return result;
}
}
/**
* @return the streamSrcIp
*/
public String getStreamSrcIp() {
return streamSrcIp;
}
/**
* @return the streamSrcPort
*/
public Integer getStreamSrcPort() {
return streamSrcPort;
}
/**
* @param streamSrcIp the streamSrcIp to set
*/
public void setStreamSrcIp(String streamSrcIp) {
this.streamSrcIp = streamSrcIp;
}
/**
* @param streamSrcPort the streamSrcPort to set
*/
public void setStreamSrcPort(Integer streamSrcPort) {
this.streamSrcPort = streamSrcPort;
}
}
public class Test {
public static void main(String[] args){
ArrayList a1=new ArrayList();
Infomas1=new Infoma(4,"172.33.2.2");
Infoma s2=new Infoma(2,"22.3.33.5");
Infoma s3=new Infoma(3,"116.56.4.3");
Infoma s4=new Infoma(4,"202.196.8.4");
a1.add(s1);
a1.add(s2);
a1.add(s3);
a1.add(s4);
//Collections.sort(a1);
Collections.sort(a1,new Student.StudentComparator());
printElements(a1);
System.out.println(Collections.max(a1));
}
}