关于Comparator接口的疑问

Pro_Vida 2006-11-25 02:59:16
为什么在以下代码中必须实现Comparable接口才能用Comparator接口进行排序?
Comparable接口和Comparator接口有什么关系吗?
import java.util.*;
class TreeSetTest
{
public static void main(String[] args)
{
TreeSet<Object> ts=new TreeSet<Object>();
ts.add(new MyStudents(2,"Vida"));
ts.add(new MyStudents(4,"Lillian"));
ts.add(new MyStudents(1,"Chaner"));
ts.add(new MyStudents(2,"Vida"));
Iterator it=ts.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}

}

}

class MyStudents implements Comparable<Object>
{
int number;
String name;
MyStudents(int number,String name)
{
this.number=number;
this.name=name;
}
public String toString()
{
return "The Student's information is: Number="+number+" name="+name;
}
public int compareTo(Object o)
{
MyStudents mst=(MyStudents)o;
return number > mst.number ? 1 : (number==mst.number ? 0 : -1);
}
class MyStudentsComparator implements Comparator<Object>
{
public int compare(Object o1,Object o2)
{
MyStudents mst1=(MyStudents)o1;
MyStudents mst2=(MyStudents)o2;
int result=mst1.number>mst2.number?1:(mst1.number==mst2.number?0:-1);
if(result==0)
{
return mst1.name.compareTo(mst2.name);
}
return result;

}
}

}
...全文
147 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
sun113 2006-11-25
  • 打赏
  • 举报
回复
mark

62,615

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧