java匿名內部類,以及實現Comparato和Comparable接口實現對對象的排序


匿名內部類的聲明使用方式,

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;
  }

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM