java基础---->hashMap的简单分析(一)
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java基础---->hashMap的简单分析(一),小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含5689字,纯文字阅读大概需要9分钟。
内容图文
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) thrownew IllegalArgumentException("Illegal initial capacity: " + initialCapacity); if (initialCapacity > MAXIMUM_CAPACITY) initialCapacity = MAXIMUM_CAPACITY; if (loadFactor <= 0 || Float.isNaN(loadFactor)) thrownew 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 } 5if (key == null) 6return putForNullKey(value); 7int hash = hash(key); // 根据key,计算它的hash值 8int i = indexFor(hash, table.length); 9for (Entry<K,V> e = table[i]; e != null; e = e.next) { 10 Object k; 11if (e.hash == hash && ((k = e.key) == key || key.equals(k))) { 12 V oldValue = e.value; 13 e.value = value; 14 e.recordAccess(this); 15return oldValue; 16 } 17 } 1819 modCount++; // 记录hashMap改变的次数20 addEntry(hash, key, value, i); 21returnnull; 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); returnnull == 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; } publicfinal K getKey() { return key; } publicfinal V getValue() { return value; } publicfinal V setValue(V newValue) { V oldValue = value; value = newValue; return oldValue; } publicfinalboolean equals(Object o) { if (!(o instanceof Map.Entry)) returnfalse; 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))) returntrue; } returnfalse; } publicfinalint hashCode() { return Objects.hashCode(getKey()) ^ Objects.hashCode(getValue()); } publicfinal 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) { } }
友情链接
的简单分析(一)' ref='nofollow'>java基础---->hashMap的简单分析(一)
原文:http://www.cnblogs.com/huhx/p/baseusejavahashmap1.html
内容总结
以上是互联网集市为您收集整理的java基础---->hashMap的简单分析(一)全部内容,希望文章能够帮你解决java基础---->hashMap的简单分析(一)所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。