我去试了试.
结果:姓名: abc,年龄: 20
姓名: aac,年龄: 20
姓名: aaa,年龄: 20
姓名: abc,年龄: 21
姓名: abc,年龄: 80
姓名: abc,年龄: 100- import java.util.Arrays;
- class Student implements Comparable<Student>{
- private String name;
- private int sum;
-
- private Student() {
- }
- private Student(String name, int sum) {
- this.name = name;
- this.sum = sum;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public int getSum() {
- return sum;
- }
- public void setSum(int sum) {
- this.sum = sum;
- }
- public String toString(){
- return "姓名:"+ this.name+"总分: "+this.sum;
- }
- @Override
- public int compareTo(Student s) {
- int num = new Integer(this.sum).compareTo(new Integer(s.sum));
- if(num==0)//分数相同
- return this.name.compareTo(s.name);//分数相同比较名字,逐个比较,
- return num;//返回的num可能是0可能是1可能是-1
- }
- }
- public class test15 {
- public static void main(String[] args) {
- Person[] per={new Person("abc", 20),new Person("aac", 20),new Person("aaa", 20),
- new Person("abc", 21),new Person("abc", 80),new Person("abc", 100),};
- Arrays.sort(per);
- for (int x = 0; x < per.length; x++) {
- System.out.println(per[x]);
- }
- }
- }
复制代码 ps:这程序确实是先比较分数,然后比较姓名,但是在比较分数的时候的升序降序控制,还有在分数相同情况下对姓名的升序降序控制,这样覆写compareTo()是无法控制的.或许本身它就不想去控制.所以它才那么写哈
{:soso_e100:} |