作者在 2016-02-23 23:33:57 发布以下内容
java中的容器排序,需要类实现Comparable接口, 同时重写该接口的compareTo( )方法。该接口只有这一种方法,当前面类的某个属性值大于后者,返回正值,等于则返回0,小于则返回负值。
import java.util.*;
class Student implements Comparable
{
String name;
int id;
public Student()
{
}
public Student(String name,int id)
{
this.name=name;
this.id=id;
}
public String toString()
{
return name+" "+id;
}
public int compareTo(Object ob)
{
Student st=(Student)ob;
if(this.id==st.id)
return 0;
else if(this.id>st.id)
return 1;
else
return -1;
}
}
public class TestJava
{
public static void main(String[] args)
{
ArrayList al=new ArrayList();
al.add(new Student("zhang",1001));
al.add(new Student("li",1008));
al.add(new Student("liu",1006));
al.add(new Student("xu",1002));
System.out.println(al);
Collections.sort(al);
System.out.println(al);
}
}