java匿名内部类,以及实现Comparato和Comparable接口实现对对象的排序

陌路散爱 提交于 2020-03-19 14:22:26

匿名内部类的声明使用方式,

Comparabletor接口实现,需要先导入包,再实现Comparator的对象比较的方法,并且需要新声明比较器类去实现此接口,再用比较器类新建对象调用compare(Objecto1, Object o2)方法,比较两个需要比较的对象的大小

Comparable的接口实现方式,可以直接使用需要比较的类去实现此接口,需要比较的对象去调用compareTo(Object o)方法即可

import java.util.Comparator;
import java.util.Arrays;

public class TestComparator{
  public static void main(String[] args){
    Student s1 = new Student(16, 'n', 99);
    Student s2 = new Student(18, 'n', 98);

    int res = s1.compareTo(s2);//根据实现接口重写的方法,对分数进行比较

    Student s3 = new Student(17, 'n', 96);
    Student[] students = new Student[3];
    students[0] = s1;
    students[1] = s2;
    students[2] = s3;
    Arrays.sort(students, new Comparator(){  //新建匿名内部类,对学生年龄进行比较
      public int compare(Object o1, Object o2){
      Student s1 = (Student)o1;
      Student s2 = (Student)o2;
      return s1.getAge() - s2.getAge(); 
      }
    });

    for (int i = 0; i <= students.length-1 ; i++) {
      System.out.println(students[i]);
    }
  }
}

class Student implements Comparable{
  public int age;
  public char gender;
  public int score;

  public Student(){

  }

  public Student(int age, char gender, int score){
    this.age = age;
    this.gender = gender;
    this.score = score;
  }

  public void setAge(int age){
    this.age = age;
  }

  public int getAge(){
    return this.age;
  }

  public void setChar(char gender){
    this.gender = gender;
  }

  public char getChar(){
    return this.gender;
  }

  public void setScore(int score){
    this.score = score;
  }

  public int getScore(){
    return this.score;
  }

  public String toString(){
    return "age: " + this.age + ", gender: " + this.gender + ", score: " + this.score;
  }

  public int compareTo(Object o){
    Student s = (Student)o;
    return this.score - s.score;
  }

}

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!