十 Java集合框架(3):Map接口

Map接口

image-20220305194118499

特点

  1. Map用于保存具有映射关系的数据:key-value(双列元素)

  2. Map中的 key 和 value 可以是任何引用类型的数据,会封装到 HashMap$Node对象中

  3. Map 中的 Key 不允许重复,原因和HashSet 一样,当有相同的key时,等价于替换

  4. Map 中的 value 可以重复

  5. Map 的key 可以为 null,value 也可以为null,注意 key 为null的只能有一个。

  6. 常用String类作为Map 的key,因为String类重写了HashCode()和equals().具体情况具体分析可以使用任意类型。

  7. key 和 value 之间存在单向一对一关系,即通过指定的 key 总能找到对应的 value

  8. Map存放数据的 key-value 示意图,一对 k-v 是放在一个Node中的,又因为Node实现了 Entry接口,有些书上也说,一对k-v是一个Entry

代码示例

Map map = new HashMap();
map.put("no1","Kobe");//OK
map.put("no2","James");//OK
System.out.println(map);//{no2=James, no1=Kobe}

map.put("no1","Curry");//当有相同的key时,等价于替换
System.out.println(map);//{no2=James, no1=Curry}

map.put("no3","Curry");//value可以相同
System.out.println(map);//{no2=James, no1=Curry, no3=Curry}

map.put(null, null);//OK
map.put(null,"Durant");//等价于替换
map.put("no4",null);//OK
System.out.println(map);//{no2=James, null=Durant, no1=Curry, no4=null, no3=Curry}

map.put(23,"Jordon");//OK
map.put(new Object(),"Pual");//OK
System.out.println(map);//{no2=James, null=Durant, no1=Curry, no4=null, no3=Curry, 23=Jordon, java.lang.Object@1b6d3586=Pual}

//通过get方法,传入key,返回对应的value
System.out.println(map.get(23));//Jordon

Map中的EntrySet

帮助理解Map的第8个特点(Map中只有Entry内部类,EntrySet 、KeySet、Values是其实现类HashMap中的内部类):

  1. k-v 最后是 HashMap$Node node = newNode(hash, key, value, null);
  2. k-v 为了方便程序员的遍历,还会创建EntrySet 集合,该集合存放的元素的类型 Entry,而一个Entry对象就有k,v 即: transient Set<Map.Entry<K,V>> entrySet;
  3. 在entrySet中,定义的类型是Map.Entry ,但是实际上存放的还是 HashMap$Node
    ,这是因为 HashMap$Node implements Map.Entry
  4. 这样当把HashMap$Node 对象存放在 EntrySet ,就方便我们的遍历 ,因为Map.Entry提供了重要方法K getKey(); V getValue();,Node对象没有这两个方法。

image-20220304171610732

Map map = new HashMap();
map.put("no1","Kobe");//k-v
map.put("no2","James");//k-v

//   K getKey(); V getValue();
Set set = map.entrySet();
System.out.println(set.getClass());//class java.util.HashMap$EntrySet
for (Object o : set) {
    System.out.print(o+" ");//no2=James no1=Kobe
}
System.out.println();

for (Object o : set) {
    //为了从HashMap$Node 取出k-v
    //1.先做一个向下转型
    Map.Entry entry = (Map.Entry) o;
    System.out.println("key:" + entry.getKey()+" - value:" + entry.getValue()+" ");
    /*输出结果
    key:no2 - value:James
    key:no1 - value:Kobe
     */
}

Set set1 = map.keySet();
System.out.println(set1.getClass());//class java.util.HashMap$KeySet
System.out.println(set1);//[no2, no1]
Collection values = map.values();
System.out.println(values.getClass());//class java.util.HashMap$Values
System.out.println(values);//[James, Kobe]

Map接口常用方法

  1. put:添加
  2. remove:根据键删除映射关系
  3. get:根据键获取值
  4. size:获取元素个数
  5. isEmpty:判断个数是否为0
  6. clear:清除
  7. containsKey:查找键是否存在
//put方法,返回值key值原先对应的value
Map map = new HashMap();
System.out.println(map.put("no1", "Kobe"));//null
System.out.println(map.put("no2","James"));//null
System.out.println(map.put("curry",null));//null
System.out.println(map.put(null,"刘亦菲"));//null
System.out.println(map.put(null,null));//刘亦菲 (替换)
System.out.println(map);//{no2=James, null=null, no1=Kobe, curry=null}

//remove(key) 返回对应的value
//remove(key,value) 返回是否成功
System.out.println(map.remove("curry"));//null
System.out.println(map.remove("no2","Curry"));//false
System.out.println(map);//{no2=James, null=null, no1=Kobe}

System.out.println(map.get("no1"));//Kobe
System.out.println(map);//{no2=James, null=null, no1=Kobe}
System.out.println(map.size());//3
System.out.println(map.isEmpty());//false
map.clear();
System.out.println(map);//{}
System.out.println(map.containsKey("java"));//false
map.put("java","no1");
System.out.println(map.containsKey("java"));//true

遍历方式

取k-v对:四种

取值:两种

//1.先取出所有的key,通过key取key-value
Set keySet = map.keySet();
//1.1 增强for循环
System.out.println("第一种方式");
for (Object key : keySet) {
    System.out.println(key+"-"+map.get(key));
}
//1.2 迭代器
System.out.println("第二种方式");
Iterator iterator = keySet.iterator();
while (iterator.hasNext()) {
    Object key =  iterator.next();
    System.out.println(key+"-"+map.get(key));
}
//2. 把所有的values取出
Collection values = map.values();
//2.1 增强for
System.out.println("第三种方式");
values.forEach(System.out::println);
//2.2 迭代器
System.out.println("第四种方式");
Iterator iterator1 = values.iterator();
while (iterator1.hasNext()) {
    Object next = iterator1.next();
    System.out.println(next);
}
//3. 通过EntrySet来获取k-v
Set entrySet = map.entrySet();
//3.1 增强for
System.out.println("第五种方式");
for (Object entry : entrySet) {
    //转换为Map.Entry对象
    Map.Entry entry1 = (Map.Entry) entry;
    System.out.println(entry1.getKey()+"-"+entry1.getValue());
}
//3.2 迭代器
System.out.println("第六种方式");
Iterator iterator2 = entrySet.iterator();
while (iterator2.hasNext()) {
    Object next =  iterator2.next();
    System.out.println(next.getClass());//class java.util.HashMap$Node
    Map.Entry entry1 = (Map.Entry) next;
    System.out.println(entry1.getKey()+"-"+entry1.getValue());
}

HashMap

特点

  1. Map接口的常用实现类:HashMap、Hashtable和Properties
  2. HashMap是Map接口使用频率最高的实现类。
  3. HashMap是以key-value对的方式来存储数据(HashMap$Node类型)。
  4. Key不能重复,但是值可以重复,允许使用null键和null值
  5. 如果添加相同的key,则会覆盖原来的key-value,等同于修改(key不会替换,val会替换)
  6. 与HashSet一样,不保证映射的顺序,因为底层是以hash表的方式来存储的。(数组+链表+红黑树)
  7. HashMap没有实现同步,因此是线程不安全的,方法上没有做同步互斥操作,没有synchronized

底层机制

image-20220306151528250

  1. (k,v)是一个Node实现了Map.Entry<K,V>,查看 HashMap的源码可以看到
  2. jdk7.0的hashmap底层实现[数组+链表], jdk8.0底层[数组+链表+红黑树]

扩容机制

HashSet的底层就是HashMap,所以两者的扩容机制相同

  1. HashMap底层维护了Node类型的数组table,默认为null
  2. 当创建对象时,将加载因子(loadfactor)初始化为0.75
  3. 当添加 key-val时,通过key的哈希值得到在table的索引。然后判断该索引处是否有元素,如果没有元素直接添加。如果该索引处有元素,继续判断该元素的key是否和准备加入的key相同,如果相等,则直接替换value;如果不相等需要判断是树结构还是链表,做出相应处理。如果添加时发现容量不够,则需扩容。
  4. 第一次添加,则需要扩容table容量为16,临界值(threshold)为12 (16 *0.75)
  5. 以后再扩容,则需要扩容table容量为原来的2倍,临界值为原来的2倍,即24,依次类推
  6. 在Java8种,如果一条链表的元素个数超过 TREEIFY_THRESHOLD(默认是8),并且table的大小 >= MIN_TREEIEF_CAPACITY(默认是64),就会进行树化(红黑树)

put()源码分析

HashMap hashMap = new HashMap();
        hashMap.put("java", 10);
        hashMap.put("php", 20);
        hashMap.put("java", 30);

        System.out.println("haseMap="+hashMap);
        /*
            源码分析
            1.执行构造器 new HashMap()
                初始化加载因子this.loadFactor = DEFAULT_LOAD_FACTOR;//0.75
                HashMap$Node[] table = null;
            2. 执行put 调用hash方法,计算key的hash值()   (h = key.hashCode()) ^ (h >>> 16);
                public V put(K key, V value) {
                    return putVal(hash(key), key, value, false, true);
                }
            3.执行putVal
                final V putVal(int hash, K key, V value, boolean onlyIfAbsent,boolean evict) {

                    // 定义辅助变量 tab、p、n、i
                    Node<K,V>[] tab; Node<K,V> p; int n, i;

                    // table 是hashMap的一个属性,类型是Node[]  存放 node节点的数组
                    // 如果 table为null或者大小为0,执行resize()方法,table第一次扩容16个空间
                    if ((tab = table) == null || (n = tab.length) == 0)
                        n = (tab = resize()).length;

                    // 取出hash值对应的table的索引位置的Node,如果为null,就直接把加入的k-v,创建成一个Node,加入该位置
                    if ((p = tab[i = (n - 1) & hash]) == null)
                        tab[i] = newNode(hash, key, value, null);
                    else {
                        Node<K,V> e; K k;
                        // 如果 table的索引位置的key的hash和新的key的hash相同,
                        // 并且满足(table现有的节点的key和准备添加的可以是同一个对象) 或者 equals返回真
                        // 就认为不能加入新的 k-v
                        if (p.hash == hash &&
                            ((k = p.key) == key || (key != null && key.equals(k))))
                            e = p;
                        else if (p instanceof TreeNode) // 如果当前table的node已经是红黑树,就按照红黑树的方式处理
                            e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
                        else {
                            // 如果找到的节点,后面是链表,就循环比较
                            for (int binCount = 0; ; ++binCount) {
                                if ((e = p.next) == null) {  // 如果整个链表,没有和他相同的,就加在该链表后
                                    p.next = newNode(hash, key, value, null);
                                    // 判断当前链表个数是否已经到8个,到8个后,进行红黑树的树化
                                    if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                                        treeifyBin(tab, hash);
                                        //如果table为null,或者大小还没有到64,暂时不树化,而是进行扩容
                                    break;
                                }
                                if (e.hash == hash &&   // 如果在循环比较过程种,如果有相同的,就直接break
                                    ((k = e.key) == key || (key != null && key.equals(k))))
                                    break;
                                p = e;
                            }
                        }
                        // 替换 value
                        if (e != null) { // existing mapping for key
                            V oldValue = e.value;
                            if (!onlyIfAbsent || oldValue == null)
                                e.value = value;
                            afterNodeAccess(e);
                            return oldValue;
                        }
                    }
                    // 操作次数,每增加一个Node,就size++
                    ++modCount;

                    // 判断是否需要扩容,threshold为扩容操作临界值,默认为12,tab超过12执行扩容
                    if (++size > threshold)
                        resize();

                    //空方法,是HashMap 给其子类留的 让其子类执行一些操作
                    afterNodeInsertion(evict);

                    // 放回 null,代表成功
                    return null;
                }
            4. 关于树化(转成红黑树)
            //如果table为null,或者大小还没有到64,暂时不树化,而是进行扩容
            //否则才会真正的树化 -> 剪枝
            final void treeifyBin(Node<K,V>[] tab, int hash) {
                int n, index; Node<K,V> e;
                if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
                    resize();
                else if ((e = tab[index = (n - 1) & hash]) != null) {
                    TreeNode<K,V> hd = null, tl = null;
                    do {
                        TreeNode<K,V> p = replacementTreeNode(e, null);
                        if (tl == null)
                            hd = p;
                        else {
                            p.prev = tl;
                            tl.next = p;
                        }
                        tl = p;
                    } while ((e = e.next) != null);
                    if ((tab[index] = hd) != null)
                        hd.treeify(tab);
                }
            }
         */

resize()源码分析

final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        int oldThr = threshold;
        int newCap, newThr = 0;
        //如果原table不为空
        if (oldCap > 0) {
        	//如果原容量已经达到最大容量了,无法进行扩容,直接返回
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            //设置新容量为旧容量的两倍
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                //阈值也变为原来的两倍
                newThr = oldThr << 1; // double threshold
        }
        /**
        * 从构造方法我们可以知道
        * 如果没有指定initialCapacity, 则不会给threshold赋值, 该值被初始化为0
    	* 如果指定了initialCapacity, 该值被初始化成大于initialCapacity的最小的2的次幂
		* 这里这种情况指的是原table为空,并且在初始化的时候指定了容量,
		* 则用threshold作为table的实际大小
		*/
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
        //构造方法中没有指定容量,则使用默认值
        else {               // zero initial threshold signifies using defaults
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        // 计算指定了initialCapacity情况下的新的 threshold
        if (newThr == 0) {
            float ft = (float)newCap * loadFactor;
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                      (int)ft : Integer.MAX_VALUE);
        }
        threshold = newThr;
    /**从以上操作我们知道, 初始化HashMap时, 
    *  如果构造函数没有指定initialCapacity, 则table大小为16
    *  如果构造函数指定了initialCapacity, 则table大小为threshold,
    *  即大于指定initialCapacity的最小的2的整数次幂

    *  从下面开始, 初始化table或者扩容, 实际上都是通过新建一个table来完成
    */ 

    @SuppressWarnings({"rawtypes","unchecked"})
    Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
    table = newTab;
    if (oldTab != null) {
        for (int j = 0; j < oldCap; ++j) {
            Node<K,V> e;
            if ((e = oldTab[j]) != null) {
              /** 这里注意, table中存放的只是Node的引用,这里将oldTab[j]=null只是清除旧表的引用, 
               * 但是真正的node节点还在, 只是现在由e指向它
               */
                oldTab[j] = null;
                //桶中只有一个节点,直接放入新桶中
                if (e.next == null)
                    newTab[e.hash & (newCap - 1)] = e;
                //桶中为红黑树,则对树进行拆分
                else if (e instanceof TreeNode)
                    ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                //桶中为链表,对链表进行拆分
                else { // preserve order
                	//下面为对链表的拆分,我们单独来讲一下。
                    Node<K,V> loHead = null, loTail = null;
                    Node<K,V> hiHead = null, hiTail = null;
                    Node<K,V> next;
                    do {
                        next = e.next;
                        if ((e.hash & oldCap) == 0) {
                            if (loTail == null)
                                loHead = e;
                            else
                                loTail.next = e;
                            loTail = e;
                        }
                        else {
                            if (hiTail == null)
                                hiHead = e;
                            else
                                hiTail.next = e;
                            hiTail = e;
                        }
                    } while ((e = next) != null);
                    if (loTail != null) {
                        loTail.next = null;
                        newTab[j] = loHead;
                    }
                    if (hiTail != null) {
                        hiTail.next = null;
                        newTab[j + oldCap] = hiHead;
                    }
                }
            }
        }
    }
    return newTab;
}

resize最重要的操作之一就是对链表的拆分了,那么resize是如何拆分链表的呢?再来看一下代码:

HashMap.Node<K,V> loHead = null, loTail = null;
HashMap.Node<K,V> hiHead = null, hiTail = null;
HashMap.Node<K,V> next;
	//遍历该桶
    do {
    next = e.next;
    //找出拆分后仍处在同一个桶中的节点
    if ((e.hash & oldCap) == 0) {
        if (loTail == null)
            loHead = e;
        else
            loTail.next = e;
        loTail = e;
    }
    else {
        if (hiTail == null)
            hiHead = e;
        else
            hiTail.next = e;
        hiTail = e;
    }
} while ((e = next) != null);
    if (loTail != null) {
    loTail.next = null;
    newTab[j] = loHead;
}
    if (hiTail != null) {
    hiTail.next = null;
    newTab[j + oldCap] = hiHead;
}

这里定义了4个变量:loHead, loTail ,hiHead , hiTail,这四个变量从字面意思可以看出应该是两个头节点,两个尾节点。那么为什么需要两个链表的头尾节点呢?看一张图就明白了:

img

这张图中index=2的桶中有四个节点,在未扩容之前,它们的 hash& cap 都等于2。在扩容之后,它们之中2、18还在一起,10、26却换了一个桶。这就是这句代码的含义:选择出扩容后在同一个桶中的节点。

 if ((e.hash & oldCap) == 0)

e.hash & oldCap == 0为什么可以判断当前节点是否需要移位, 而不是再次计算hash,假设oldCap = 8,newCap为16,则原来桶的索引计算为e.hash & (oldCap-1),新的桶计算为e.hash & (newCap-1),发现其实两者的差别就是e.hash & oldCap

old (8-1):   111
new (16-1): 1111 = 111 + 1000 (oldCap=1000)

如图计算结果,8(oldCap)的二进制为:1000

2的二进制为:0010 & 1000 =0000
10的二进制为:1010,1010 & 1000 = 1000,
18的二进制为:10010, 10010 & 1000 = 0000,
26的二进制为:11010,11010 & 1000 = 1000,

从与操作后的结果可以看出来,2和18应该在同一个桶中,10和26应该在同一个桶中。

所以lo和hi这两个链表的作用就是保存原链表拆分成的两个链表。找到拆分后仍处于同一个桶的节点,将这些节点重新连接起来。

然后将拆分完的链表放进桶里的操作,比较简单,只需要将头节点放进桶里就ok了,newTab[j]和newTab[j + oldCap]分别代表了扩容之后原位置与新位置,就相当于之前那张图中的2和10。

resize()总结

  • 什么时候进行resize操作?

    1. 初始化table;
    2. 在size超过threshold之后进行扩容
  • 扩容后的新数组容量为多大比较合适?

    • 扩容后的数组应该为原数组的两倍,并且这里的数组大小必须是2的幂
  • 节点在转移的过程中是一个个节点复制还是一串一串的转移?

    • 从源码中我们可以看出,扩容时是先找到拆分后处于同一个桶的节点,将这些节点连接好,然后把头节点存入桶中即可

⭐️总结一下加入相同hash值元素(equals不相同)的过程:带色的是加入的第几个元素:

0 1 16 9 32 10 64 11 树化

如果不发生树化的table大小变化,括号内为阈值(threshold)

if (++size > threshold)
    resize();

0 => 16(12) => 32(24) =>64(64*0.75=48)=>128(96)=>…=>1 << 30(Integer.MAX_VALUE)

HashTable

基本介绍

  1. 存放的元素是键值对:K-V
  2. Hashtable的键和值都不能为null,否则会抛出NullPointerException
  3. Hashtable使用方法基本上和 hashMap一样
  4. Hashtable是线程安全的(synchorized),hashMap 是线程不安全的

源码分析

Hashtable table = new Hashtable();
table.put("john",100);
//table.put(null,100);   //NullPointerException
//table.put("join",null);  //NullPointerException
table.put("lucy",100);
table.put("lic",100);
table.put("lic",80); // 替换
table.put("hello1",1);
table.put("hello2",1);
table.put("hello3",1);
table.put("hello4",1);
table.put("hello5",1);
table.put("hello6",1);
table.put("hello7",1);
System.out.println(table);
/*
Hashtable底层:
1. 底层有一个数组 Hashtable$Entry[]  初始化大小为11
2. 临界值 threshold 8 = 11 * 0.75
3. 扩容:按照自己的扩容机制运行
4. put()中发现无相同元素时,执行 addEntry(hash, key, value, index); 添加 k-v 封装到 Entry
5. 当 if(count >= threshold) 满足时,没加之前table的count,就进行扩容
6. 按照 int newCapacity = (oldCapaticy << 1 ) + 1;  即[old*2+1]的大小扩容
*/

HashMap与HashTable的比较

版本线程安全(同步)效率允许null键null值
HashMap1.2不安全可以
Hashtable1.0安全较低不可以

Properties

基本介绍

  1. Properties类继承HashTable类并且实现了Map接口,也是使用一种键值对的形式来保存数据。
  2. 他的使用特点和Hashtable类似
  3. Properties 还可以从 xxx.properties 文件中,加载数据到Properties类对象,并进行读取和修改
  4. 说明:xxx.properties 文件通常作为配置文件

Java读写Properties配置文件:https://www.cnblogs.com/xudong-bupt/p/3758136.html

代码示例

//        1. Properties 继承自 Hashtable
//        2. 可以通过 k-v 存放数据, key和value不能为空

Properties properties = new Properties();
properties.put("john",100);
//        properties.put(null,100);  //NullPointerException
//        properties.put("john",null); //NullPointerException
properties.put("lucy",100);
properties.put("lic",100);
properties.put("lic",80);

System.out.println(properties);

//        通过 key 获取对应的值
System.out.println(properties.get("lic"));
//        删除
properties.remove("lic");
System.out.println(properties);

//        修改
properties.put("john","wkliu");
System.out.println(properties);

TreeMap

基本介绍

  • 唯一
  • 有序(按照升序或降序排列)
  • 底层:二叉树,key遵照二叉树特点
  • key对应的类型内部一定要实现比较器(内部比较器,外部比较器自选)
public class TreeMap_ {
    public static void main(String[] args) {

//       使用默认构造器,创建TreeMap
//        TreeMap treeMap = new TreeMap();

//
        TreeMap treeMap = new TreeMap(new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
//                按照传入的 k(String) 的大小进行排序
//                return ((String) o2).compareTo((String) o1);
//                按照字符串长度大小排序
                return ((String) o1).length() - ((String) o2).length();


            }
        });
        treeMap.put("jack","杰克");
        treeMap.put("tom","汤姆");
        treeMap.put("wkliul","拉拉");
        treeMap.put("smith","史密斯");
        treeMap.put("smith","123");
        System.out.println(treeMap.size());
        System.out.println(treeMap);
    }
}

原理

通过节点对象属性,按照排序规则判断元素的对象,指定子节点的位置

image-20211029182030983

源码

  • 节点类型: private transient Entry<K,V> root;//根节点
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 TreeMap() {
            comparator = null;   // 如果使用空构造器,那么底层就不使用外部比较器
     }
    public TreeMap(Comparator<? super K> comparator) {
            this.comparator = comparator;   // 如果使用有参构造器,就相当于指定了外部比较器
        }
    
  • put方法

    public V put(K key, V value) {   // k,v的类型在创建对象时就指定了
        // 首次添加元素 ,t的值为null    
        Entry<K,V> t = root; // 第二次添加节点时,root已经是跟节点了
    
        	if (t == null) {
                // 自己跟自己比
                compare(key, key); // type (and possibly null) check
    			//跟节点确定为root
                root = new Entry<>(key, value, null);
                size = 1;
                modCount++;
                return null;
            }
            int cmp;
            Entry<K,V> parent;
            // split comparator and comparable paths
        	// 将外部比较器 赋给 cpr
            Comparator<? super K> cpr = comparator;
        //  cpr 不等于 null, 意味着创建对象时调用了有参构造器,指定了外部比较器
            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);
            }
            //  cpr 等于 null, 意味着创建对象时调用了 空构造器,没有指定外部比较器,会使用内部比较器
            else {
                if (key == null)
                    throw new NullPointerException();
                @SuppressWarnings("unchecked")
                    Comparable<? super K> k = (Comparable<? super K>) key;
                do {//遍历所有的key
                    parent = t;
                    cmp = k.compareTo(t.key);  //将元素的key值作比较
                    // cpm 返回的值为int类型的值
                    if (cmp < 0)
                        t = t.left;
                    else if (cmp > 0)
                        t = t.right;
                    else  // cmp == 0 
                        // 表示两个key 一样,key不变(key唯一),将原来的value替换为新的value
                        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;
        }
    

如何选择集合实现类

在开发中,选择什么集合实现类,主要取决于业务操作特点,然后根据集合实现类特性进行选择,分析如下:

1)先判断存储的类型(一组对象[单列]或一组键值对[双列)

2)一组对象[单列]:Collection接口

  • 允许重复:List
    • 增删多:LinkedList [底层维护了一个双向链表]
    • 改查多:ArrayList [底层维护Object类型的可变数组]
  • 不允许重复: Set
    • 无序:HashSet[底层是HashMap,维护了一个哈希表即(数组+链表+红黑树)]
    • 排序:TreeSet
    • 插入和取出顺序一致: LinkedHashSet,维护数组+双向链表

3)一组键值对: Map

  • 键无序: HashMap [底层是:哈希表 jdk7: 数组+链表,jdk8:数组+链表+红黑树]
  • 键排序:TreeMap
  • 健插入和取出顺序一致:LinkedHashMap
  • 读取文件:Properties
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值