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. static class Entry<K,V> implements Map.Entry<K,V> {
  3. final K key;
  4. V value;
  5. Entry<K,V> next;
  6. final int hash;
  7. ……
  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. for (int i = 0; i < len; i++) {
  21. h = 31*h + val[off++];
  22. }
  23. hash = h;
  24. }
  25. return h;
  26. }

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. * Returns index for hash code h.
  17. */
  18. static int indexFor(int h, int length) {
  19. return h & (length-1);
  20. }
时间: 2024-07-31 14:18:41

Java HashMap HashCode的相关文章

Java HashMap拾遗

Java HashMap拾遗 @author ixenos 零碎知识 尽量返回接口而非实际的类型,如返回List.Set.Map而非ArrayList.HashSet.HashMap,便于更换数据结构,而客户端代码不用改变.这就是针对抽象编程 Map.entrySet 方法返回Map映射的 Set 视图Set<Map.Entry<K,V>>,维护entry键值对 该 set 受Map映射支持,所以对Map映射的更改可在此 set 中反映出来,反之亦然! 如果对该 set 进行迭代的

[翻译]Java HashMap工作原理

大部分Java开发者都在使用Map,特别是HashMap.HashMap是一种简单但强大的方式去存储和获取数据.但有多少开发者知道HashMap内部如何工作呢?几天前,我阅读了java.util.HashMap的大量源代码(包括Java 7 和Java 8),来深入理解这个基础的数据结构.在这篇文章中,我会解释java.util.HashMap的实现,描述Java 8实现中添加的新特性,并讨论性能.内存以及使用HashMap时的一些已知问题. 内部存储 Java HashMap类实现了Map<K

java 翻盖hashCode()深入探讨 代码示例

package org.rui.collection2.hashcode; /** * 覆盖hashcode * 设计HashCode时最重要的因素 就是:无论何时,对同一个对象调用HashCode都应该产生同样的值, * 如果你的HashCode方法依赖于对象中易变的数据,用户就要当心了,因为此数据发生变化 时 * HashCode就会生成一个不同的散列码,相当于产生一个不同的健 * 此外 也不应该使HashCode依赖于具有唯一性的对象信息,尤其是使用this的值,这只能很糟糕, * 因为这

【转】Java HashMap工作原理(好文章)

大部分Java开发者都在使用Map,特别是HashMap.HashMap是一种简单但强大的方式去存储和获取数据.但有多少开发者知道HashMap内部如何工作呢?几天前,我阅读了java.util.HashMap的大量源代码(包括Java 7 和Java 8),来深入理解这个基础的数据结构.在这篇文章中,我会解释java.util.HashMap的实现,描述Java 8实现中添加的新特性,并讨论性能.内存以及使用HashMap时的一些已知问题. 内部存储 Java HashMap类实现了Map<K

【转】Java HashMap 源码解析(好文章)

- .fluid-width-video-wrapper { width: 100%; position: relative; padding: 0; } .fluid-width-video-wrapper iframe, .fluid-width-video-wrapper object, .fluid-width-video-wrapper embed { position: absolute; top: 0; left: 0; width: 100%; height: 100%; } [

Java Map hashCode深究

[Java心得总结七]Java容器下——Map 在自己总结的这篇文章中有提到hashCode,但是没有细究,今天细究整理一下hashCode相关问题 1.hashCode与equals 首先我们都知道hashCode()和equals()函数是java基类Object的一部分,我查阅了java7文档,其中对于两者的描述如下: 解读这里对hashCode的描述,不难发现: 首先hashCode必须是一个整数,即Integer类型的 其次满足一致性,即在程序的同一次执行无论调用该函数多少次都返回相同

转:Java HashMap实现详解

Java HashMap实现详解 转:http://beyond99.blog.51cto.com/1469451/429789 1.    HashMap概述: HashMap是基于哈希表的Map接口的非同步实现.此实现提供所有可选的映射操作,并允许使用null值和null键.此类不保证映射的顺序,特别是它不保证该顺序恒久不变. 2.    HashMap的数据结构: 在java编程语言中,最基本的结构就是两种,一个是数组,另外一个是模拟指针(引用),所有的数据结构都可以用这两个基本结构来构造

[Java] HashMap、TreeMap、Hashtable排序

Java中对Map(HashMap,TreeMap,Hashtable等)的排序时间 首先简单说一下他们之间的区别: HashMap: 最常用的Map,它根据键的HashCode 值存储数据,根据键可以直接获取它的值,具有很快的访问速度.HashMap最多只允许一条记录的键为Null(多条会覆盖);允许多条记录的值为 Null.非 首先简单说一下他们之间的区别: HashMap: 最常用的Map,它根据键的HashCode 值存储数据,根据键可以直接获取它的值,具有很快的访问速度.HashMap

关于Java集合hashCode的总结

Java集合的hashCode是一个重要的知识点,在我们学习Java的过程中,也许会比较迷茫,所以这篇文章就给大家总结了一下. hashCode 的作用 在 Java 集合中有两类,一类是 List,一类是 Set 他们之间的区别就在于 List 集合中的元素师有序的,且可以重复,而 Set 集合中元素是无序不可重复的.对于 List 好处理,但是对于 Set 而言我们要如何来保证元素不重复呢?通过迭代来 equals() 是否相等.数据量小还可以接受,当我们的数据量大的时候效率可想而知(当然我