package package1; import java.util.Map.Entry; import java.util.Set; import java.util.TreeMap; public class TreeMapDemo6 { public static void main(String[] args) { TreeMap<String, String> temp=new TreeMap<>(); temp.put("aa", "bb"); temp.put("cc", "dd"); temp.put("ee", "ff"); temp.put("gg", "hh"); System.out.println(temp); //對temp進行封裝 Set<Entry<String, String>> entry = temp.entrySet(); //加強for循環輸出 for(Entry<String, String> entrys:entry) { System.out.println(entrys.getKey()+"----"+entrys.getValue()); } } } 實例: package package1; import java.util.TreeMap; public class Demo4 { public static void main(String[] args) { TreeMap<Person, String> temp=new TreeMap<Person, String>(); /*Person person1=new Person("zhangsan", 20); Person person2=new Person("lisi", 30); Person person3=new Person("wangwu", 40); Person person4=new Person("zhaoliu", 50);*/ temp.put(new Person("zhangsan", 20), "aa"); temp.put(new Person("lisi", 30), "bb"); temp.put(new Person("wangwu", 40), "cc"); temp.put(new Person("zhaoliu", 50), "dd"); System.out.println(temp); } } class Person implements Comparable<Person>{ private String name; private int age; public Person(String name,int age) { this.name=name; this.age=age; } 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; } @Override public int compareTo(Person o) { // TODO Auto-generated method stub if (this.age-o.getAge()>0) { return 1; }else if(this.age-o.getAge()<0){ return -1; } return 0; } }