TreeMap

通过使用红黑树实现Map接口

  提供按排序顺序存储键/值对的有效手段,同时允许快速检索

TreeMap实现SortedMap并且扩展AbstractMap,它本身并没有定义其他方法

@Override
比较
public int compareTo(Employee o) { if(this.age-o.getAge()>0) { return 1; }else if (this.age-o.getAge()<0){ return -1; } return 0; }
package com.day1;

import java.util.Comparator;
import java.util.TreeMap;

public class TreeMapDemo2 {
     public static void main(String[] args) {
        TreeMap<Employee, String> pMap=new TreeMap<Employee, String>(new Comparator<Employee>() {

            @Override
            public int compare(Employee o1, Employee o2) {
                if (o1.getAge()-o2.getAge()>0) {
                    return 1;
                }else if (o1.getAge()-o2.getAge()<0) {
                    return -1;
                } 
                return 0;
            }
        });
     
        pMap.put(new Employee("张三", 20), "zhangsan");
        pMap.put(new Employee("李四", 26), "lisi");
        pMap.put(new Employee("王五", 23), "wangwu");
        pMap.put(new Employee("玫瑰", 22), "wangwu");
        System.out.println(pMap);
    }
}

class Employee  implements Comparable<Employee>{
    private String name;
    private int age;
    public Employee(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(Employee o) {
        if(this.age-o.getAge()>0) {
         return 1;    
        }else if (this.age-o.getAge()<0){
         return -1;    
        }
        return 0;
    }
    
    
}

  

原文地址:https://www.cnblogs.com/tanlei-sxs/p/9986703.html