0
点赞
收藏
分享

微信扫一扫

对对象进行排序

zhongjh 2022-04-14 阅读 48
java-ee
List<Student> students = new ArrayList<>();
        students.add(new Student("张三",89));
        students.add(new Student("李四",95));
        students.add(new Student("王五",92));
        students.add(new Student("王二",74));
        System.out.println("Student:" + students );
        Collections.sort(students);
        System.out.println("排序后:"+students);

Student类

package com.hqyj.api.collections;

import java.util.Objects;

public class Student implements Comparable{
    private  String name;
    private  Integer score;

    public Student() {
    }

    public Student(String name, Integer score) {
        this.name = name;
        this.score = score;
    }

    public String getName() {
        return name;
    }

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

    public Integer getScore() {
        return score;
    }

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

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

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        return Objects.equals(name, student.name) &&
                Objects.equals(score, student.score);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, score);
    }

    @Override
    public int compareTo(Object o) {
        Student s = (Student) o;//向下造型
        /**
         * 怎么将从大到小,转换为从小到大---->交换两个对象的计算位置
         *   -从小到大 this.getScore() - s.getScore()
         *   -从大到小   s.getScore() - this.getScore()
         */
        return s.getScore() - this.getScore() ;
    }
}

举报

相关推荐

0 条评论