Discuss / Java / 实现Comparable接口,覆写compareTo方法

实现Comparable接口,覆写compareTo方法

Topic source
import java.util.*;

public class Test {
    public static void main(String[] args) {
        Map<Student, Integer> map = new TreeMap<>();
        map.put(new Student("Tom", 77), 1);
        map.put(new Student("Bob", 66), 2);
        map.put(new Student("Lily", 99), 3);
        for (Student key : map.keySet()) {
            System.out.println(key);
        }
        System.out.println(map.get(new Student("Bob", 66)));
    }
}

class Student implements Comparable {
    public String name;
    public int score;
    
    public Student(String name, int score) {
        this.name = name;
        this.score = score;
    }
    
    public String toString() {
        return String.format("{%s: score=%d}", name, score);
    }

    @Override
    public int compareTo(Object o) {
        Student s = (Student)o;
        if (this.score == s.score) {
            return 0;
        }
        return this.score > s.score ? -1 : 1;
    }
}

  • 1

Reply