标签:
TreeMap,与TreeSet类似,可以对集合中的元素进行排序,同时保持元素的唯一性。
应注意,Comparable(实现接口,记得覆盖comparaTo方法),Comparator的使用。
1 import java.util.Iterator; 2 import java.util.TreeMap; 3 4 import cn.itcast.p2.bean.Student; 5 import cn.itcast.p3.comparator.ComparatorByName; 6 7 public class TreeMapDemo { 8 9 public static void main(String[] args) { 10 TreeMap<Student,String> tm = new TreeMap<Student,String>(new ComparatorByName()); 11 12 tm.put(new Student("lisi",38), "北京"); 13 tm.put(new Student("zhaoliu",24), "上海"); 14 tm.put(new Student("xiaoqiang",31), "沈阳"); 15 tm.put(new Student("wangcai",38), "大连"); 16 tm.put(new Student("zhaoliu",24), "铁岭"); 17 18 Iterator<Student> it = tm.keySet().iterator(); 19 while (it.hasNext()) 20 { 21 Student key = it.next(); 22 String value = tm.get(key); 23 System.out.println(key.getName()+":"+key.getAge()+"--"+value); 24 } 25 26 27 } 28 29 }
标签:
原文地址:http://www.cnblogs.com/Newbie-Cai/p/5812052.html