TreeMap<Person,String>:
因为TreeMap是二叉树(红黑树)结构,所以需要做自然排序或者比较器排序。
- package com.kxg.TreeMap;
- import java.util.Comparator;
- import java.util.Set;
- import java.util.TreeMap;
- import com.kxg.HashMap.Person;
- public class TreeMap2 {
- public static void main(String[] args) {
- // 创建集合对象
- // TreeMap<Person,String>
- TreeMap<Person, String> hm = new TreeMap<Person, String>(
- new Comparator<Person>() {
- @Override
- public int compare(Person s1, Person s2) {
- int num = s1.getAge() - s2.getAge();
- int num2 = num == 0 ? s1.getName().compareTo(
- s2.getName()) : num;
- return num2;
- }
- });
- // 创建对象
- Person p = new Person("李延旭", 20);
- Person p2 = new Person("任兴亚", 23);
- Person p3 = new Person("赵磊", 19);
- Person p4 = new Person("王澳", 20);
-
- // 添加元素
- hm.put(p, "商丘");
- hm.put(p2, "漯河");
- hm.put(p3, "信阳");
- hm.put(p4, "周口");
-
- Set<Person> set = hm.keySet();
- for(Person key : set)
- {
- String value = hm.get(key);
- System.out.println(key.getName() + ":" + key.getAge() + "=="
- + value);
- }
- }
- }
复制代码
|