实现Comparable接口,覆写compareTo方法
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))); // null? } } class Student implements Comparable<Student> { public String name; public int score; Student(String name, int score) { this.name = name; this.score = score; } @Override public int compareTo(Student o) { Student p = (Student) o; if (this.score == p.score) { return 0; } return this.score < p.score ? -1 : 1; } public String toString() { return String.format("{%s: score=%d}", name, score); } }
Sign in to make a reply
爱竹子的大黑熊
实现Comparable接口,覆写compareTo方法