• HashMap记录


    1、HashMap是一个散列表,存储的是key-value键值对

        不同步的,线程不安全的,key 和 value都可以为 null,不是有序的

        两个参数:初始容量、加载因子(0.75),哈希表中的条目数超出了加载因子与当前容量的乘积时,则要对该哈希表进行 rehash 操作(即重建内部数据结构)

    2、插入

    1  HashMap<String , Double> map = new HashMap<String , Double>(); 
    2  map.put("语文" , 80.0); 
    3  map.put("数学" , 89.0); 
    4  map.put("英语" , 98.2); 

        HashMap 类中 put(K key, V value)方法的源代码是:

     1  public V put(K key, V value) 
     2  { 
     3      // 如果 key 为 null,调用 putForNullKey 方法进行处理
     4      if (key == null) 
     5          return putForNullKey(value); 
     6      // 根据 key 的 keyCode 计算 Hash 值
     7      int hash = hash(key.hashCode()); 
     8      // 搜索指定 hash 值在对应 table 中的索引
     9       int i = indexFor(hash, table.length);
    10      // 如果 i 索引处的 Entry 不为 null,通过循环不断遍历 e 元素的下一个元素
    11      for (Entry<K,V> e = table[i]; e != null; e = e.next) 
    12      { 
    13          Object k; 
    14          // 找到指定 key 与需要放入的 key 相等(hash 值相同
    15          // 通过 equals 比较放回 true)
    16          if (e.hash == hash && ((k = e.key) == key 
    17              || key.equals(k))) 
    18          { 
    19              V oldValue = e.value; 
    20              e.value = value; 
    21              e.recordAccess(this); 
    22              return oldValue; 
    23          } 
    24      } 
    25      // 如果 i 索引处的 Entry 为 null,表明此处还没有 Entry 
    26      modCount++; 
    27      // 将 key、value 添加到 i 索引处
    28      addEntry(hash, key, value, i); 
    29      return null; 
    30  } 

         其中一个重要的内部接口:Map.Entry,每个 Map.Entry 其实就是一个 key-value 对。

     

  • 相关阅读:
    LightOJ1031 Easy Game(区间DP)
    POJ1325 Machine Schedule(二分图最小点覆盖集)
    ZOJ1654 Place the Robots(二分图最大匹配)
    LightOJ1025 The Specials Menu(区间DP)
    POJ2288 Islands and Bridges(TSP:状压DP)
    LightOJ1021 Painful Bases(状压DP)
    LightOJ1013 Love Calculator(DP)
    POJ1780 Code(欧拉路径)
    POJ1201 Intervals(差分约束系统)
    ZOJ2770 Burn the Linked Camp(差分约束系统)
  • 原文地址:https://www.cnblogs.com/yml6/p/7678826.html
Copyright © 2020-2023  润新知