集合-TreeMap详解和TreeSet详解以及两者的区别

时间:2025-04-03 19:52:51
public class Person1 implements Comparable<Person1> { private int age; private String name; public Person1(String name, int age) { this.name = name; this.age = age; } @Override public int compareTo(Person1 o) { return this.age-o.age; } @Override public String toString() { return name+":"+age; } } public class TreeMapDemo{ public static void main(String [] args){ Map<Person1,Integer> map = new TreeMap<>(); Person1 person1 = new Person1("zzh",18); Person1 person2 = new Person1("jj",17); Person1 person3 = new Person1("qq",19); map.put(person1, 1); map.put(person2, 2); map.put(person3, 3); for(Entry<Person1, Integer> entry:map.entrySet()){ System.out.println(entry.getKey()+":"+entry.getValue()); } } } //测试结果: //jj:17:2 //zzh:18:1 //qq:19:3