HashTable之put

来源:互联网 发布:类似菠萝饭的软件 编辑:程序博客网 时间:2024/05/18 08:40
package lattice;import java.util.Hashtable;public class TestHashTable{public static void main(String[] args){Hashtable<String, Integer>hashtable=new Hashtable<>();String str=new String("w3ang");hashtable.put(str,1);hashtable.put(str,2);hashtable.put("xd", 3);hashtable.put("hn", 3);//System.out.println(hashtable.keySet().toString());System.out.println(hashtable.entrySet().toString());//Out:[w3ang=2, xd=3, hn=3]}}


源码:

/**     * Maps the specified <code>key</code> to the specified     * <code>value</code> in this hashtable. Neither the key nor the     * value can be <code>null</code>. <p>     *     * The value can be retrieved by calling the <code>get</code> method     * with a key that is equal to the original key.     *     * @param      key     the hashtable key     * @param      value   the value     * @return     the previous value of the specified key in this hashtable,     *             or <code>null</code> if it did not have one     * @exception  NullPointerException  if the key or value is     *               <code>null</code>     * @see     Object#equals(Object)     * @see     #get(Object)     */    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;    }


0 0
原创粉丝点击