温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

HashTable源码分析

发布时间:2020-06-19 23:18:00 来源:网络 阅读:227 作者:mufeng07 栏目:编程语言

/**

  • The hash table data.
    */
    //存放键值对的数组
    private transient Entry<?,?>[] table;

    /**

  • The total number of entries in the hash table.
    */
    //大小
    private transient int count;

    /**

  • The table is rehashed when its size exceeds this threshold. (The
  • value of this field is (int)(capacity * loadFactor).)
  • @serial
    */
    //阀值
    private int threshold;

    /**

  • The load factor for the hashtable.
  • @serial
    */
    //负载因子
    private float loadFactor;
    //默认初始容量为11,负载因子0.75
    public Hashtable() {
    this(11, 0.75f);
    }

    //1.8版本没有修改,没有维护红黑树结构
    public synchronized V put(K key, V value) {
    // Make sure the value is not null
    if (value == null) {
    throw new NullPointerException();
    }

    // Makes sure the key is not already in the hashtable.
    Entry<?,?> tab[] = table;
    int hash = key.hashCode();
    //求余获得索引
    int index = (hash & 0x7FFFFFFF) % tab.length;
    @SuppressWarnings("unchecked")
    Entry<K,V> entry = (Entry<K,V>)tab[index];
    for(; entry != null ; entry = entry.next) {
        if ((entry.hash == hash) && entry.key.equals(key)) {
            V old = entry.value;
            entry.value = value;
            return old;
        }
    }
    
    addEntry(hash, key, value, index);
    return null;

    }

    /**

  • Removes the key (and its corresponding value) from this
  • hashtable. This method does nothing if the key is not in the hashtable.
  • @param key the key that needs to be removed
  • @return the value to which the key had been mapped in this hashtable,
  • or <code>null</code> if the key did not have a mapping
  • @throws NullPointerException if the key is <code>null</code>
    */
    public synchronized V remove(Object key) {
    Entry<?,?> tab[] = table;
    int hash = key.hashCode();
    int index = (hash & 0x7FFFFFFF) % tab.length;@SuppressWarnings("unchecked")
    br/>@SuppressWarnings("unchecked")
    for(Entry<K,V> prev = null ; e != null ; prev = e, e = e.next) {
    if ((e.hash == hash) && e.key.equals(key)) {
    modCount++;
    if (prev != null) {
    prev.next = e.next;
    } else {
    tab[index] = e.next;
    }
    count--;
    V oldValue = e.value;
    e.value = null;
    return oldValue;
    }
    }
    return null;
    }
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI