面试题如下
56、TreeMap和TreeSet在排序时如何比较元素?Collections工具类中的sort()方法如何比较元素?
答:TreeSet要求存放的对象所属的类必须实现Comparable接口,该接口提供了比较元素的compareTo()方法,当插入元素时会回调该方法比较元素的大小。TreeMap要求存放的键值对映射的键必须实现Comparable接口从而根据键对元素进行排序。
从上可得出放入TreeSet跟TreeMap的对象一定要实现Comparable?
有如下2个问题
- 本人写了一段测试代码,发现如果对象不实现该接口一样可以放进去 2.如果不实现该接口放进去的话,对象有序吗。
代码如下
import java.util.*;
public class Leetcode {
public static void main(String[] agrs){
Map<Integer,Student> map = new TreeMap<>();
Student student = new Student();
map.put(1,student);
Set<Student> set = new TreeSet<>();
set.add(student);
}
}
public class Student {
private String name;
private int age;
private int 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 int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
}