Java HashMap HashCode

1.HashMap

  《1》遍历:HashMap无序遍历

    for(Map.Entry<String, String>m: map.entrySet()//键值对,允许键为空String
        {
            System.out.println(m.getKey()+" : "+m.getValue());
        }

 HashMap 源码:

  1. transient Entry[] table;  
  2.    
  3. static class Entry<K,V> implements Map.Entry<K,V> {  
  4.     final K key;  
  5.     V value;  
  6.     Entry<K,V> next;  
  7.     final int hash;  
  8.     ……  

添加元素

    1. public V put(K key, V value) {  
    2.    // HashMap允许存放null键和null值。  
    3.    // 当key为null时,调用putForNullKey方法,将value放置在数组第一个位置。  
    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.        Object k;  
    13.       // 如果发现 i 索引处的链表的某个Entry的hash和新Entry的hash相等且两者的key相同,则新Entry覆盖旧Entry,返回。  
    14.        if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {  
    15.            V oldValue = e.value;  
    16.            e.value = value;  
    17.            e.recordAccess(this);  
    18.            return oldValue;  
    19.        }  
    20.    }  
    21.    // 如果i索引处的Entry为null,表明此处还没有Entry。  
    22.    modCount++;  
    23.    // 将key、value添加到i索引处。  
    24.    addEntry(hash, key, value, i);  
    25.    return null; 

读取元素

   

  1. public V get(Object key) {  
  2.     if (key == null)  
  3.         return getForNullKey();  
  4.     int hash = hash(key.hashCode());  
  5.     for (Entry<K,V> e = table[indexFor(hash, table.length)];  
  6.         e != null;  
  7.         e = e.next) {  
  8.         Object k;  
  9.         if (e.hash == hash && ((k = e.key) == key || key.equals(k)))  
  10.             return e.value;  
  11.     }  
  12.     return null;  
  13. }

String equals

   

  1.  /** 
  2.     * Compares this string to the specified object.  The result is {@code 
  3.     * true} if and only if the argument is not {@code null} and is a {@code 
  4.     * String} object that represents the same sequence of characters as this 
  5.     * object. 
  6.     * 
  7.     * @param  anObject 
  8.     *         The object to compare this {@code String} against 
  9.     * 
  10.     * @return  {@code true} if the given object represents a {@code String} 
  11.     *          equivalent to this string, {@code false} otherwise 
  12.     * 
  13.     * @see  #compareTo(String) 
  14.     * @see  #equalsIgnoreCase(String) 
  15.     */  
  16.    public boolean equals(Object anObject) {  
  17. if (this == anObject) {  
  18.     return true;  
  19. }  
  20. if (anObject instanceof String) {  
  21.     String anotherString = (String)anObject;  
  22.     int n = count;  
  23.     if (n == anotherString.count) {  
  24.     char v1[] = value;  
  25.     char v2[] = anotherString.value;  
  26.     int i = offset;  
  27.     int j = anotherString.offset;  
  28.     while (n-- != 0) {  
  29.         if (v1[i++] != v2[j++])  
  30.         return false;  
  31.     }  
  32.     return true;  
  33.     }  
  34. }  
  35. return false;  
  36.    } 

String hashcode

  1.   /** 
  2.     * Returns a hash code for this string. The hash code for a 
  3.     * <code>String</code> object is computed as 
  4.     * <blockquote><pre> 
  5.     * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] 
  6.     * </pre></blockquote> 
  7.     * using <code>int</code> arithmetic, where <code>s[i]</code> is the 
  8.     * <i>i</i>th character of the string, <code>n</code> is the length of 
  9.     * the string, and <code>^</code> indicates exponentiation. 
  10.     * (The hash value of the empty string is zero.) 
  11.     * 
  12.     * @return  a hash code value for this object. 
  13.     */  
  14.    public int hashCode() {  
  15. int h = hash;  
  16.        int len = count;  
  17. if (h == 0 && len > 0) {  
  18.     int off = offset;  
  19.     char val[] = value;  
  20.   
  21.            for (int i = 0; i < len; i++) {  
  22.                h = 31*h + val[off++];  
  23.            }  
  24.            hash = h;  
  25.        }  
  26.        return h;  
  27.    } 

hash函数

  1. /** 
  2.     * Applies a supplemental hash function to a given hashCode, which 
  3.     * defends against poor quality hash functions.  This is critical 
  4.     * because HashMap uses power-of-two length hash tables, that 
  5.     * otherwise encounter collisions for hashCodes that do not differ 
  6.     * in lower bits. Note: Null keys always map to hash 0, thus index 0. 
  7.     */  
  8. tatic int hash(int h) {  
  9.        // This function ensures that hashCodes that differ only by  
  10.        // constant multiples at each bit position have a bounded  
  11.        // number of collisions (approximately 8 at default load factor).  
  12.        h ^= (h >>> 20) ^ (h >>> 12);  
  13.        return h ^ (h >>> 7) ^ (h >>> 4);  
  14.    }  
  15.   
  16.    /** 
  17.     * Returns index for hash code h. 
  18.     */  
  19.  static int indexFor(int h, int length) {  
  20.        return h & (length-1);  

转载于:https://www.cnblogs.com/HackHer/p/5079492.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java HashMap是一个散列表,用于存储键值对的映射关系。它实现了Map接口,根据键的HashCode值来存储数据,具有非常快速的访问速度。HashMap允许一条记录的键为null,但是键是唯一的,即同一个键只能对应一个值。 例如,下面的代码展示了如何使用Java HashMap: Map<Integer, String> map = new HashMap<>(); map.put(1, "a"); map.put(2, "b"); map.put(3, "c"); 这段代码创建了一个HashMap对象,并将键值对存储在其中。键的类型是Integer,值的类型是String。通过put()方法可以向HashMap中添加键值对。 此外,Java HashMap还提供了其他常用的方法,如get()方法用于通过键获取对应的值,remove()方法用于移除指定键对应的键值对等等。HashMap的内部实现使用了哈希表来实现高效的数据存储和访问。 需要注意的是,HashMap是非线程安全的,如果在多线程环境中使用,需要采取额外的措施来保证线程安全性。另外,在序列化和反序列化HashMap对象时需要特殊处理,可以通过自定义readObject()和writeObject()方法来实现。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [Java HashMap](https://download.csdn.net/download/weixin_38588592/13705053)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* *3* [JavaHashMap 详解](https://blog.csdn.net/java1527/article/details/126850576)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值