1.实现Comparable接口
2.覆盖comparaTo方法----用传来的参数和实例本身的属性去比
class Father implements Comparable
{
public int age;
String name; @Override
public int compareTo(Object o) {
Father f=(Father)o;
int res=this.age-f.age;
if(res!=0)
{
res=this.name.compareTo(f.name);
}
return res;
}3.Collections.sort(list);调用系统排序
public static void main(String[] args)
{
List<Father> list =new LinkedList<Father>();
list.add(new Father(23, "f"));
list.add(new Father(20, "a"));
list.add(new Child(22, "z"));
Collections.sort(list);
for(int i=0;i<list.size();i++)
{
Father f=list.get(i);
System.out.println(f);
}
}
本文介绍如何通过实现Comparable接口并覆盖compareTo方法来定义Java对象之间的排序规则。通过具体示例,展示如何对包含不同年龄和姓名的对象列表进行排序。
535

被折叠的 条评论
为什么被折叠?



