zoukankan      html  css  js  c++  java
  • java基础---->hashMap的简单分析(一)

      HashMap是一种十分常用的数据结构对象,可以保存键值对。它在项目中用的比较多,今天我们就来学习一下关于它的知识。据说那些你一笑就跟着你笑的人,不是傻逼就是爱你的人。

    HashMap的简单使用

    一、hashMap的put和get方法

    Map<String, String> map = new HashMap<>();
    map.put("username", "huhx");
    map.put("password", "1234");
    map.put(null, null);
    System.out.println(map.put("username", "linux")); // huhx,这里会返回
    System.out.println(map.get("username")); // linux
    System.out.println(map.get(null) + " size: " + map.size()); // null size: 3

    put(key, value)方法如果map中存在根据hash计算key的值。那么返回的结果是map中oldValue值。但是map里面的key对应的值更新成了value值。

    二、hashMap的putAll方法

    public void putAll(Map<? extends K, ? extends V> m) {
        ......
        for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
            put(e.getKey(), e.getValue());
    }

    三、hashMap中的clear方法

    clear()方法会清空map里面所有的数据,map的大小为0。

    public void clear() {
        modCount++;
        Arrays.fill(table, null);
        size = 0;
    }

     四、hashMap中的remove方法

    注意以下的两个方法是接着上述的map而言的。

    System.out.println(map.remove("username") + ", size: " + map.size()); // linux, size: 2
    System.out.println(map.remove("nokey") + ", size: " + map.size()); // null, size: 2

    源码的方法remove方法如下:

    public V remove(Object key) {
        Entry<K,V> e = removeEntryForKey(key);
        return (e == null ? null : e.value);
    }

    五、hashMap中的containKey方法

    检查是否map中存在对应的key。

    public boolean containsKey(Object key) {
        return getEntry(key) != null;
    }

    map的几种遍历方式

    Map<String, String> map = new HashMap<>();我们Map用到了泛型,这里注明一下。

     一、hashmap中的entrySet() 遍历

    Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
    while (iterator.hasNext()) {
        Map.Entry<String, String> entry = iterator.next();
        String key = entry.getKey();
        String value = entry.getValue();
        System.out.println("key=" + key + " value=" + value);
    }

    二、For-Each循环entrySet

    for (Map.Entry<String, String> entry : map.entrySet()) {
        String key = entry.getKey();
        String value = entry.getValue();
        System.out.println("key=" + key + " value=" + value);
    }

    三、 For-Each循环keySet

    for (String key : map.keySet()) {
        System.out.println("key=" + key + " value=" + map.get(key));
    }

     对于以上的各种,由于map可以存储key为null的数据。所以在遍历map取key的时候,如果是string。最好是cast强转,而不是调用toString()方法。

    hashMap原理的简单说明

    一、hashMap的数据存储在一个Entry数组中,new HashMap();会设置hashMap的初始容量为16,负载因子为0.75。

    public HashMap(int initialCapacity, float loadFactor) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " + initialCapacity);
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " + loadFactor);
    
        this.loadFactor = loadFactor;
        threshold = initialCapacity;
        init();
    }

      其中init()方法可以供实现HashMap的子类重写,当初始化map时增加自己的处理逻辑。hashMap里面的数据都是通过以下的数组完成的,正因为是数组,所以效率比较高。

    transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE;

    二、hashMap主要涉及键值对的put和get,这里我们讨论它的put方法

     1 public V put(K key, V value) {
     2     if (table == EMPTY_TABLE) {
     3         inflateTable(threshold); // 如果table数组为空,就初始化为大小为16,负载因子为0.75的数组。
     4     }
     5     if (key == null)
     6         return putForNullKey(value);
     7     int hash = hash(key); // 根据key,计算它的hash值
     8     int i = indexFor(hash, table.length);
     9     for (Entry<K,V> e = table[i]; e != null; e = e.next) {
    10         Object k;
    11         if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
    12             V oldValue = e.value;
    13             e.value = value;
    14             e.recordAccess(this);
    15             return oldValue;
    16         }
    17     }
    18 
    19     modCount++; // 记录hashMap改变的次数
    20     addEntry(hash, key, value, i);
    21     return null;
    22 }

    第9行到15行,处理的是put的key已经存在时,处理的逻辑。就是返回oldValue,更新key的新值为value。这里我们主要看addEntry方法。

    void addEntry(int hash, K key, V value, int bucketIndex) {
        if ((size >= threshold) && (null != table[bucketIndex])) {
            resize(2 * table.length);
            hash = (null != key) ? hash(key) : 0;
            bucketIndex = indexFor(hash, table.length);
        }
    
        createEntry(hash, key, value, bucketIndex);
    }

      由于hashMap里面维护的数组在创建的时候,大小为16。当key越来越多的时候,明显计算的bucketIndex(table数组的下标)会重复。也就是bucketIndex即将要插入的位置已经有了数据。当发生这种情况时,会增加一倍hashMap的容量,重新计算hash和要插入数组的位置。最后的createEntry方法如下,把key,value的值存放到table数组中。

    void createEntry(int hash, K key, V value, int bucketIndex) {
        Entry<K,V> e = table[bucketIndex];
        table[bucketIndex] = new Entry<>(hash, key, value, e);
        size++;
    }

     以下附上hashMap的get代码:

    public V get(Object key) {
        if (key == null)
            return getForNullKey();
        Entry<K,V> entry = getEntry(key);
    
        return null == entry ? null : entry.getValue();
    }

     table数组的数据类型Entry类如下:

    static class Entry<K,V> implements Map.Entry<K,V> {
        final K key;
        V value;
        Entry<K,V> next;
        int hash;
    
        /**
         * Creates new entry.
         */
        Entry(int h, K k, V v, Entry<K,V> n) {
            value = v;
            next = n;
            key = k;
            hash = h;
        }
    
        public final K getKey() {
            return key;
        }
    
        public final V getValue() {
            return value;
        }
    
        public final V setValue(V newValue) {
            V oldValue = value;
            value = newValue;
            return oldValue;
        }
    
        public final boolean equals(Object o) {
            if (!(o instanceof Map.Entry))
                return false;
            Map.Entry e = (Map.Entry)o;
            Object k1 = getKey();
            Object k2 = e.getKey();
            if (k1 == k2 || (k1 != null && k1.equals(k2))) {
                Object v1 = getValue();
                Object v2 = e.getValue();
                if (v1 == v2 || (v1 != null && v1.equals(v2)))
                    return true;
            }
            return false;
        }
    
        public final int hashCode() {
            return Objects.hashCode(getKey()) ^ Objects.hashCode(getValue());
        }
    
        public final String toString() {
            return getKey() + "=" + getValue();
        }
    
        /**
         * This method is invoked whenever the value in an entry is
         * overwritten by an invocation of put(k,v) for a key k that's already
         * in the HashMap.
         */
        void recordAccess(HashMap<K,V> m) {
        }
    
        /**
         * This method is invoked whenever the entry is
         * removed from the table.
         */
        void recordRemoval(HashMap<K,V> m) {
        }
    }
    Entry

    友情链接

  • 相关阅读:
    素敵な日本人 2-1
    十年目のバレンタインデー のほか
    水晶の数珠  3
    水晶の数珠  2
    STM32 USB HID BarCodeReader不兼容问题的解决
    水晶の数珠 1
    クリスマスミステリ 2
    クリスマスミステリ 1
    サファイア奇跡 3
    感悟成功
  • 原文地址:https://www.cnblogs.com/huhx/p/baseusejavahashmap1.html
Copyright © 2011-2022 走看看