实体类Student类代码如下所示:
package com.test.Test11; public class Student implements Comparable<Student>{ private int age; private String name; private Double height; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Double getHeight() { return height; } public void setHeight(Double height) { this.height = height; } public Student(int age, String name, Double height) { this.age = age; this.name = name; this.height = height; } @Override public String toString() { return "Student{" + "age=" + age + ", name='" + name + '\'' + ", height=" + height + '}'; } @Override public int compareTo(Student o) { /* //按照年龄排序 return this.getAge()-o.getAge();*/ //按照姓名排序 return this.getName().compareTo(o.getName()); } } 测试类Test.java如下所示:
package com.test.Test11; import java.util.TreeMap; public class Test03 { public static void main(String[] args) { //TreeMap 唯一,有序(按升序或者降序排序) TreeMap<Student, Integer> map = new TreeMap<>(); map.put(new Student(19,"blili",170.5), 1001); map.put(new Student(18,"blili",150.5), 1003); map.put(new Student(19,"alili",180.5), 1023); map.put(new Student(17,"clili",140.5), 1671); map.put(new Student(10,"dlili",160.5), 1891); System.out.println(map.size()); //4(上面的添加了5对数据,只出来4对数据) //按照age升序排列 System.out.println(map); //按照年龄排序{Student{age=10, name='dlili', height=160.5}=1891, Student{age=17, name='clili', height=140.5}=1671, Student{age=18, name='blili', height=150.5}=1003, Student{age=19, name='blili', height=170.5}=1023} //按照姓名排序 {Student{age=19, name='alili', height=180.5}=1023, Student{age=19, name='blili', height=170.5}=1003, Student{age=17, name='clili', height=140.5}=1671, Student{age=10, name='dlili', height=160.5}=1891} } }