30.Camparable

发表日期:2022-08-05 16:54:10 | 来源: | | 浏览(758) 分类:JAVA基础

CamparableDemo01

class Student implements Comparable<Student>{
   private String name;
   private int age;
   private float score;
   
   public Student(String name,int age,float score){
      this.name = name;
      this.age = age;
      this.score = score;
   }
   
   public String toString(){
      return name + "\t\t" + this.age + "\t\t" + this.score;
   }
   public int compareTo(Student stu){
      if(this.score>stu.score){
         return -1;
      }else if(this.score<stu.score){
         return 1;
      }else{
         if(this.age>stu.age){
            return 1;
         }else if(this.age<stu.age){
            return -1;
         }else{
            return 0;
         }
      }
   }
}
public class CamparableDemo01 {

   public static void main(String args[]) {
      Student stu[] = {
            new Student("张三",20,90.0f),
            new Student("李四",21,92.0f),
            new Student("王五",24,88.3f),
            new Student("赵六",19,86.1f),
            new Student("孙七",23,76.1f)
      };
      for(int i=0;i<stu.length;i++){
         System.out.println(stu[i]);
      }
      
      java.util.Arrays.sort(stu);
      
      System.out.println("<<<<<<Campare>>>>>>");
      
      for(int i=0;i<stu.length;i++){
         System.out.println(stu[i]);
      }

   }

}


集速网 copyRight © 2015-2022 宁ICP备15000399号-1 宁公网安备 64010402001209号
与其临渊羡鱼,不如退而结网
欢迎转载、分享、引用、推荐、收藏。