代码:
public class Demo01 {
public static void main(String[] args) {
//新建集合
TreeMap<Student,String> treeMap=new TreeMap<>();
//1.添加
Student s1=new Student("孙悟空",100);
Student s2=new Student("猪八戒",101);
Student s3=new Student("唐僧",102);
treeMap.put(s1,"大师兄");
treeMap.put(s2,"三师兄");
treeMap.put(s3,"师父");
System.out.println("元素个数: "+treeMap.size());
System.out.println(treeMap.toString());
}
}
输出:
根据报错,类型转化异常,不能比较,因此需要实现Comparable接口,所以对代码中的Student类进行修改.
完成Student类修改后,运行成功: