Java 中对类进行排序的方法(转)

JAVA中的比较器接口Comparable用于数组对象的排序,要使用此功能,必须让类继承自Comparable接口,重写compareTo(Object obj)方法。

import java.util.*;

class Person implements Comparable{
private String name;
private int age;
private float score;
public Person(String name,int age,float score){
   this.name=name;
   this.age=age;
   this.score=score;
   }
   public String toString(){
    return "姓名:"+this.name+", 年龄:"+this.age+", 成绩:"+this.score;
    }
    public int compareTo(Object obj){
     Person p = (Person)obj;
     if(p.score>this.score){
      return 1;
      }
      else if(p.score<this.score){
       return -1;
       }
       else{
        if(p.age>this.age){
         return 1;
         }
         else if(p.age<this.age){
         return -1;
        }
         else{
          return 0;
          }
        }
     }
}
public class OODemo35{
   public static void main(String []args){
    Person p[] = new Person[5];
    p[0] = new Person("张三 ",23,96);
    p[1] = new Person("张三2",24,96);
    p[2] = new Person("张三3",21,94);
    p[3] = new Person("张三4",22,98);
    p[4] = new Person("张三5",20,89);
   
    Arrays.sort(p);
    for(int x=0;x<p.length;x++){
     System.out.println(p[x]);
     }   
    }
   }

输出结果:

姓名:张三4, 年龄:22, 成绩:98.0
姓名:张三2, 年龄:24, 成绩:96.0
姓名:张三 , 年龄:23, 成绩:96.0
姓名:张三3, 年龄:21, 成绩:94.0
姓名:张三5, 年龄:20, 成绩:89.0

转载于:https://www.cnblogs.com/Sikaozhe/p/4946875.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值