Discuss / Java / 【笔记】-TreeMap中key实现compareTo方法

【笔记】-TreeMap中key实现compareTo方法

Topic source

实现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);
    }
}

  • 1

Reply