Java集合类学习--TreeMap(一)

23 篇文章 0 订阅

概述

TreeMap使用红黑树存储元素,可以保证元素按key值的大小进行遍历。
在这里插入图片描述
TreeMap 类的继承结构如下:在这里插入图片描述
可以看出:

public class TreeMap<K,V>
    extends AbstractMap<K,V>
    implements NavigableMap<K,V>, Cloneable, java.io.Serializable

TreeMap实现了Map、SortedMap、NavigableMap、Cloneable、Serializable等接口。

代码分析

成员变量

/**
 * The comparator used to maintain order in this tree map, or
 * null if it uses the natural ordering of its keys.
 *
 * TreeMap 内部的比较器,若为空,则为自然顺序。
 */
private final Comparator<? super K> comparator;

// 根节点,TreeMap没有桶的概念,所有的元素都存储在一颗树中。
private transient Entry<K,V> root;

/**
 * The number of entries in the tree.元素个数
 */
private transient int size = 0;

/**
 * The number of structural modifications to the tree.修改次数
 */
private transient int modCount = 0;

构造器

TreeMap 有四个构造器,分别如下:

/**
 * 无参构造器。使用 key 的自然顺序排列(key 要实现 Comparable 接口)
 */
public TreeMap() {
    comparator = null;
}

/**
 * 使用指定的 Comparator(比较器)构造一个空的 TreeMap
 */
public TreeMap(Comparator<? super K> comparator) {
    this.comparator = comparator;
}

/**
 * 使用给定的 Map 构造一个 TreeMap
 */
public TreeMap(Map<? extends K, ? extends V> m) {
    comparator = null;
    putAll(m);
}

/**
 * 使用给定的 SortedMap 构造一个 TreeMap
 *(使用 SortedMap 的顺序)
 */
public TreeMap(SortedMap<K, ? extends V> m) {
    comparator = m.comparator();
    try {
        buildFromSorted(m.size(), m.entrySet().iterator(), null, null);
    } catch (java.io.IOException cannotHappen) {
    } catch (ClassNotFoundException cannotHappen) {
    }
}

构造方法主要分成两类,一类是使用comparator比较器,一类是key必须实现Comparable接口。

Entry内部类

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;
}

先简单学习这些基本信息,常用方法后续学习补充…

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值