接口 Comparable<T>

类型参数:T - 可以与此对象进行比较的那些对象的类型

public interface Comparable<T>

此接口强行对实现它的每个类的对象进行整体排序。这种排序被称为类的自然排序,类的 compareTo 方法被称为它的自然比较方法

实现此接口的对象列表(和数组)可以通过 Collections.sort(和 Arrays.sort)进行自动排序。实现此接口的对象可以用作有序映射中的键或有序集合中的元素,无需指定比较器

负整数、零或正整数,根据此对象是小于、等于还是大于指定对象。

compareTo(对象)
if(this. > ) return -1; //高到低排序

例子:学生分数高到低,年龄低到高排序

package com.ij34;

/**
 * Created by Admin on 2018/3/7.
 */
public class Student implements Comparable<Student>{
    private String name;
    private  int age;
    private  float score;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

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

    public float getScore() {
        return score;
    }

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

    public Student(String name, int age, float score) {
        this.name = name;
        this.age = age;
        this.score = score;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", score=" + score +
                '}';
    }

    @Override
    public int compareTo(Student o) {
        if (this.score > o.score) return -1;
        else if (this.score < o.score) return 1;
         else{
            if (this.age > o.age) return 1;
            else if (this.age < o.age) return -1;
            else return 0;
        }
    }
}
View Code

相关文章:

  • 2021-12-21
  • 2022-12-23
  • 2021-08-01
  • 2021-07-07
猜你喜欢
  • 2022-01-12
  • 2021-12-27
  • 2021-09-21
  • 2022-12-23
  • 2022-12-23
  • 2021-05-28
  • 2021-12-30
相关资源
相似解决方案