原 自学JVAVA---(39)--(内功心法【37】)TreeMap

TreeMap
【小城贝尔】
底层红黑树,键值来相助。
左右类中笼,含父定黑红。
数据存入池,键将顺序执。
排序自定义,接口做膀臂。

TreeMap底层是红黑树

//TreeMap 源码
 static final class Entry<K,V> implements Map.Entry<K,V> {
        K key;
        V value;
        Entry<K,V> left;
        Entry<K,V> right;
        Entry<K,V> parent;
        boolean color = BLACK;
public class TreeMapDemo {
    public static void main(String[] args) {
        TreeMap<Integer ,String >  tm = new TreeMap<>();
        tm.put(4,"尔");
        tm.put(3,"贝");
        tm.put(1,"小");
        tm.put(2,"城");
        System.out.println(tm);//{1=小, 2=城, 3=贝, 4=尔}  key会排序

        TreeMap<Student ,String> tr = new TreeMap<>();
        tr.put(new Student(111,"guo",3000),"java");
        tr.put(new Student(333,"li" ,1000),"is");
        tr.put(new Student(333,"li" ,1000),"is");
        tr.put(new Student(333,"li" ,2000),"is");
        tr.put(new Student(333,"li" ,3000),"is");
        tr.put(new Student(30,"cheng",5000),"good");
        tr.put(new Student(500,"can" ,300),"very");
        tr.put(new Student(999,"fly" ,1000),"nice");
        System.out.println(tr);


    }
}

class Student implements  Comparable<Student>{
    private Integer id;
    private String name;
    private Integer salary;

    public Student(Integer id, String name, Integer salary) {
        this.id = id;
        this.name = name;
        this.salary = salary;
    }

    @Override
    public int compareTo(Student o) {
        if(this.id > o.id){
            return  1;
        }else  if(this.id <= o.id){
            return  -1;
        }else if(this.salary > o.salary){
            return  1;
        }else  if(this.salary <= o.salary){
            return  -1;
        }
        return  0;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", salary=" + salary +
                '}';
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值