容器——TreeMap

TreeMap底层数据结构是红黑树

键是唯一、有序的(升序)

常用的方法和HashMap一样。

在使用自定义对象作为key时,必须具备比较规则

常用构造方法:

(1)外部比较器的构造方法

public TreeMap(Comparator<? super K> comparator) {

        this.comparator = comparator;

    }

       (2)无参构造

   public TreeMap() {

        comparator = null;

    }

 

 

TreeMap的键是有序的升序排列,这是怎么做到的?

首先键值是个String类型的字符串,而String类型实现了Comparable<String>接口,这是内部比较器。使用了内部比较器的comareTo的方法.

public int compareTo(String anotherString) {

        int len1 = value.length;

        int len2 = anotherString.value.length;

        int lim = Math.min(len1, len2);

        char v1[] = value;

        char v2[] = anotherString.value;

 

        int k = 0;

        while (k < lim) {

            char c1 = v1[k];

            char c2 = v2[k];

            if (c1 != c2) {

                return c1 - c2;

            }

            k++;

        }

        return len1 - len2;

    }

如果我们不想根据字母的升序排序,想用其他规则进行排序呢?比如根据键值的字符长度排序

这时我们可以用外部比较器去实现。

创建TreeMap对象,使用前面的第一个构造方法创建对象。

自己写一个类继承Comparator,编写自己的规则。

问号处填comLength 

 这样TreeMap的键值就可以根据你写的外部比较器进行排序了。

TreeMap怎么知道用外部比较器还是内部比较器呢?

// split comparator and comparable paths

        Comparator<? super K> cpr = comparator;

        if (cpr != null) {  //外部

            do {

                parent = t;

                cmp = cpr.compare(key, t.key);

                if (cmp < 0)

                    t = t.left;

                else if (cmp > 0)

                    t = t.right;

                else

                    return t.setValue(value);

            } while (t != null);

        }

        else {  //内部

            if (key == null)

                throw new NullPointerException();

            @SuppressWarnings("unchecked")

                Comparable<? super K> k = (Comparable<? super K>) key;

            do {

                parent = t;

                cmp = k.compareTo(t.key);

                if (cmp < 0)

                    t = t.left;

                else if (cmp > 0)

                    t = t.right;

                else

                    return t.setValue(value);

            } while (t != null);

        }

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值