要排序一个对象数组,要实现一个接口:Comparable,在这个接口中有一个方法,compareTo()
class Student implements Comparable
{
int num;
String name;
Student(int num,String name)
{
this.num=num;
this.name=name;
}
public String toString()
{
return "number="+num+","+"name="+name;
}
public int compareTo(Object o)
{
Student s=(Student)o;
//return num>s.num ? 1 : (num==s.num ? 0 : -1);
int result=num>s.num ? 1 : (num==s.num ? 0 : -1);
if(0==result)
{
result=name.compareTo(s.name);
}
return result;
}
}
阅读(388) | 评论(0) | 转发(0) |