Java map容器

HashMap

HashMap:底层结构是哈希表。查询快、 添加快,无序
key:无序,唯一 HashSet
value:无序,不唯一 Collection

LinkedHashMap

LinkedHashMap:底层结构是哈希表+链表。查询快、添加快,有序
key:有序(添加顺序),唯一 LinkedHashSet
value:无序,不唯一 Collection

TreeMap

TreeMap:底层结构是红黑树,速度介于哈希表和线性表之间,有序
key:有序(自然顺序)唯一TreeSet
value:无序不唯一 Collection
节点结构:
在这里插入图片描述

构造方法

无参,不指定比较器

public TreeMap() {
    comparator = null;
}

put源码

  1. 先判断根节点是否有值

    没有就直接在根节点进行插入
    (添加过程就是构造二叉平衡树的过程,会自动平衡)

  2. 有就看是否有外部比较器
    有外部比较器根据外部比较器规则对树进行遍历,是否已存在key,存在则进行值覆盖,不存在根据比较器规则就在左子树或右子树插入key-value。
    无就使用内部比较器规则,插入。

public V put(K key, V value) {
    Entry<K,V> t = root;
    //根节点为空
    if (t == null) {
        compare(key, key); // type (and possibly null) check

        root = new Entry<>(key, value, null);
        size = 1;
        modCount++;
        return null;
    }
    int cmp;
    Entry<K,V> parent;
    // 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);
    }
    Entry<K,V> e = new Entry<>(key, value, parent);
    if (cmp < 0)
        parent.left = e;
    else
        parent.right = e;
    fixAfterInsertion(e);
    size++;
    modCount++;
    return null;
}

常用方法

增加

map.put(key,value);

查询

String value = map.get(key);//通过key获得值
map.entrySet()//获取key-value组合的entry
map.keySet()//获取键的集合

删除

map.remove(key)//根据key删除
map.clear()//删除全部

修改

map.replace(key,value)//替换指定key对应的值

其他方法

map.size()//map元素个数
map.isEmpty() //是否为空
map.containsKey()//是否包含某个key

map没有迭代器,无法使用迭代器直接遍历,需要先变成Set,再遍历Set
Entry: Map接口中的内部接口

遍历

遍历HashMap

//        直接获取keyset,遍历keyset,get得到值
for (String key:
     map.keySet()) {
    System.out.println(map.get(key));
}

推荐使用以下???

//        通过Iterator遍历,返回的Entry接口
Set<Entry<String, String>> set=map.entrySet();
Iterator<Entry<String,String>> it=set.iterator();
while (it.hasNext()){
    	Entry<String,String> e=it.next();
    	System.out.println(e.getValue());
	}
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值