java 自定义对象 排序,Java对自定义对象实现排序,实现Comparable接口

有时,我们会需要对一个存放自定义bean对象的列表进行排序。

举例讲解,如List,其中Student有grade(年级)和score(分数)属性,要求先按照grade升序,若grade一样,再按照score降序排序。

定义Student类时,需实现Comparable接口,重写compareTo方法:

/*

* Student类

* name,grade、score两个属性

*/

public class Student implements Comparable{

private String name;

private int grade;

private int score;

@Override

public int compareTo(Student o)

{

if (null == o)

{

return -1;

}

// grade小的排前面

if (this.grade < o.getGrade())

{

return -1;

// grade大的排后面

} else if (this.grade > o.getGrade())

{

return 1;

// 若grade相同,则比较score

} else

{

// score小的排后面

if (this.score < o.getScore())

{

return 1;

// score大的排前面

} else if (this.score > o.getScore())

{

return -1;

} else

{

return 0;

}

}

}

@Override

public String toString()

{

return this.name + "," + this.grade + "," + this.score;

}

/*

* getter and setter

*/

}

其中compareTo(Student o)方法中,若this.grade同理,this.score编写测试类:

public class TestSort

{

public static void main(String[] args)

{

Liststulist = new ArrayList();

// 初始化学生对象,添加到list中

stulist.add(new Student("Curry", 4, 95));

stulist.add(new Student("Harden", 5, 92));

stulist.add(new Student("James", 5, 94));

stulist.add(new Student("Kobe", 6, 91));

stulist.add(new Student("Durant", 4, 94));

stulist.add(new Student("Rose", 5, 97));

// 利用Collections工具进行排序

Collections.sort(stulist);

// 输出验证

for (Student s : stulist)

{

System.out.println(s);

}

}

}

控制台输出结果:

7d6d6c620a77bbf2df67202f76ee20cc.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值