HashMap不足性分析
不足性:
1.缺陷就在于其高度依赖hash算法,如果key是自定义类,你得自己重写hashcode方法,写hash算法。
而且hashmap要求,存入时的hashcode什么样,之后就不能在变更,如果一个类的hashcode与其成员变量name有关,而之后name又发生了变化,那么hashmap行为将不正常。
两个对象如果equals相同,那hashcode的值一定相同,如果hashcode值相同,对象不一定equals相同,只能证明两对象在散列存储中处于同一位置! 在散列存储中存放元素,通常先判断hash值,确定是不是在这个位置,再判断equals 和已存放的元素是否相等。
所以hash值又必须跟对象属性有关系,否则无法保证equals相等 hash就等,但和属性挂钩,一旦属性变化,hash就变化,处于散列存储的位置就会发生变化
2.hashmap的元素存储位置,除了元素key的hash值有关,还跟数组本身长度有关,如果扩容数组长度发生变化,必须把所有元素重新计算其index存放位置,所以尽可能事先确定hashmap的大小,防止扩容
1、基本概念:
Hash散列:通过hash算法转换成一个固定值
Map:x,y 地图
通过Hash值定位到Map,将Value存进去
存储方式:k:v方式。键值对
key可以为空,null当成一个key来存储
2、源码分析:
1、static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
默认的初始容量2的4次方
2、static final int MAXIMUM_CAPACITY = 1 << 30;
最大容量为2的30次方
3、static final float DEFAULT_LOAD_FACTOR = 0.75f;
加载因子:0.75f,是指容量达到容器的4分之3时,进行扩容
4、int threshold;
入口初始化--扩容的变量
5、transient Node<K,V>[] table;
第一次使用时初始化,并根据需要调整大小。当分配时,长度总是2的幂
6、transient Set<Map.Entry<K,V>> entrySet;
保存缓存entrySet (),用来存取key、values
7、transient int size;
此映射中包含的键值映射的数目
8、transient int modCount;
用来记录被修改的次数
9、final float loadFactor;
临时的加载因子
/**
*initialCapacity:初始容量
*loadFactor:加载因子
*/
10、public HashMap(int initialCapacity, float loadFactor)
一个有参的构造方法
11、public HashMap(int initialCapacity)
12、public HashMap()
初始化加载因子
13、public HashMap(Map<? extends K, ? extends V> m)
实现了地图。putAll和Map构造函数。
14、 public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
将指定值与此映射中的指定键关联。如果映射以前包含键的映射,则替换旧值。
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
15、 public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
--键值参数实体类
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next;
Node(int hash, K key, V value, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
public final K getKey() { return key; }
public final V getValue() { return value; }
public final String toString() { return key + "=" + value; }
public final int hashCode() {
return Objects.hashCode(key) ^ Objects.hashCode(value);
}
public final V setValue(V newValue) {
V oldValue = value;
value = newValue;
return oldValue;
}
public final boolean equals(Object o) {
if (o == this)
return true;
if (o instanceof Map.Entry) {
Map.Entry<?,?> e = (Map.Entry<?,?>)o;
if (Objects.equals(key, e.getKey()) &&
Objects.equals(value, e.getValue()))
return true;
}
return false;
}
}
--根据健查找容器中是否存在的key,有则返回V,无则返回null
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
if ((e = first.next) != null) {
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
Entry对象: Table:数组+链表 数据结构
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
if (oldCap > 0) {
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
threshold = newThr;
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
if (oldTab != null) {
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else { // preserve order
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do {
next = e.next;
if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
else {
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
3、手写HashMap源码:
顶层接口Map:
package com.cq.hashmap;
/**
*
* @author M
*
* @param <K>
* @param <V>
*/
public interface Map<K,V> {
/**
* 内容添加
* @param k
* @param v
* @return
*/
public V put(K k,V v);
/**
* 根据key获取最新内容
* @param k
* @return
*/
public V get(K k);
/**
* 获取容器内容数量
* @return
*/
public int size();
/**
* 实体类接口
* @author Administrator
*
* @param <K>
* @param <V>
*/
public interface Entry<K, V>{
public K getKey();
public V getValue();
}
}
实现类HashMap<k,v>
package com.cq.hashmap;
public class HashMap<K,V> implements Map<K, V> {
// 默认容器
private static int defaultlegth = 1 << 4;
// 加载因子
private static float defaultLoder = 0.75f;
private Entry[] table = null;
private int size = 0;
public HashMap() {
this(defaultlegth, defaultLoder);
}
public HashMap(int length, float defaultLoder2) {
defaultlegth = length;
defaultLoder = defaultLoder2;
table = new Entry[defaultlegth];
}
public V put(K k, V v) {
size++;
int index = hash(k);
Entry<K, V> entry = table[index];
if (entry == null) {
table[index] = newEntry(k, v, null);
} else {
table[index] = newEntry(k, v, entry);
}
return (V) table[index].getValue();
}
public Entry<K, V> newEntry(K k, V v, Entry<K, V> next) {
return new Entry<K,V>(k, v, next);
}
private Integer hash(K k) {
int len = defaultlegth;
int i = k.hashCode() % len;
return i >= 0 ? i : -i;
}
public V get(K key) {
int index = hash(key);
if (table[index] == null) {
return null;
}
return (V) find(key, table[index]);
}
private V find(K key, Entry<K, V> entry) {
if (key == entry || key.equals(entry.getKey())) {
if (entry.next != null) {
System.out.println("旧值:" + entry.next.getValue());
}
return entry.getValue();
} else {
if (entry.next != null) {
System.out.println("旧值:" + entry.next.getValue());
find(key, entry.next);
}
}
return null;
}
public int size() {
return size;
}
class Entry<K, V> implements Map.Entry<K, V> {
K k;
V v;
Entry<K, V> next;
public Entry(K k, V v, Entry<K, V> next) {
super();
this.k = k;
this.v = v;
this.next = next;
}
public K getKey() {
return k;
}
public V getValue() {
return v;
}
}
}
测试类:
package com.cq.hashmap;
import org.junit.Test;
public class TestMap {
@Test
public void MapTest() {
Map<String, Integer> map=new HashMap<String, Integer>();
long currentTimeMillis = System.currentTimeMillis();
for (int i = 0; i < 1000; i++) {
map.put("悟空"+i,i);
}
for (int i = 0; i < 1000; i++) {
System.out.println(map.get("悟空"+i));
}
long currentTimeMillis2 = System.currentTimeMillis();
System.out.println("大小:"+map.size()+"时间:"+(currentTimeMillis2-currentTimeMillis));
}
}
不足之处:(伸缩性)
1、伸缩性
2、时间复杂度:你的hash算法决定了你的效率
3、Key是否重复有关get(0)1
4、当hash扩容是,需要重新去add entry数组里面。
当需要多少容量时,最好先指定扩容大小,防止在put的时候进行扩容很多次
HashMap不足性分析的更多相关文章
- MINIX3 内核整体架构回顾及内核定 性分析
MINIX3 内核整体架构回顾及内核定 性分析 12.1 注意事项 由于本文档不对 I/O 文件系统做出分析,所以在此不对 MINIX3 整体做出一个分 析,本章主要是针对内核进程分析.并且这里的模 ...
- 连续型变量的推断性分析——t检验
连续型变量的推断性分析方法主要有t检验和方差分析两种,这两种方法可以解决一些实际的分析问题,下面我们分别来介绍一下这两种方法 一.t检验(Student's t test) t检验也称student ...
- 【JAVA集合】HashMap源码分析(转载)
原文出处:http://www.cnblogs.com/chenpi/p/5280304.html 以下内容基于jdk1.7.0_79源码: 什么是HashMap 基于哈希表的一个Map接口实现,存储 ...
- Java中HashMap源码分析
一.HashMap概述 HashMap基于哈希表的Map接口的实现.此实现提供所有可选的映射操作,并允许使用null值和null键.(除了不同步和允许使用null之外,HashMap类与Hashtab ...
- 基础进阶(一)之HashMap实现原理分析
HashMap实现原理分析 1. HashMap的数据结构 数据结构中有数组和链表来实现对数据的存储,但这两者基本上是两个极端. 数组 数组存储区间是连续的,占用内存严重,故空间复杂的很大.但数组的二 ...
- JDK1.8 HashMap源码分析
一.HashMap概述 在JDK1.8之前,HashMap采用数组+链表实现,即使用链表处理冲突,同一hash值的节点都存储在一个链表里.但是当位于一个桶中的元素较多,即hash值相等的元素较多时 ...
- HashMap源码分析和应用实例的介绍
1.HashMap介绍 HashMap 是一个散列表,它存储的内容是键值对(key-value)映射.HashMap 继承于AbstractMap,实现了Map.Cloneable.java.io.S ...
- 【Java】HashMap源码分析——常用方法详解
上一篇介绍了HashMap的基本概念,这一篇着重介绍HasHMap中的一些常用方法:put()get()**resize()** 首先介绍resize()这个方法,在我看来这是HashMap中一个非常 ...
- 【Java】HashMap源码分析——基本概念
在JDK1.8后,对HashMap源码进行了更改,引入了红黑树.在这之前,HashMap实际上就是就是数组+链表的结构,由于HashMap是一张哈希表,其会产生哈希冲突,为了解决哈希冲突,HashMa ...
随机推荐
- Ubuntu16.04安装Supervisor
安装 sudo apt-get install supervisor 启动,否则会报 unix:///tmp/supervisor.sock no such file service supervis ...
- qt model/view/delegate
Qt Model/View理解(一)---构造model https://blog.csdn.net/weixin_42303052/article/details/89233887 Qt Model ...
- Retrofit 二次封装实践
首先感谢这位大神的博客:https://blog.csdn.net/u014569233/article/details/67639522,在他的基础上根据自己项目进行了修改最后成为现在项目使用的样子 ...
- oracle 在列名后的 (+)是什么意思,如何转换为mysql
外连接的意思select *from a,bwhere a.id=b.id(+)意思就是返回a,b中匹配的行 和 a中有但是b中没有的行. 参考https://www.cnblogs.com/Aaro ...
- SQL SERVER 日志写入原理浅析
昨天看到网上有一个关于SQL SERVER 课件,便随手下载了下来看看主要讲了些什么内容,于是看到了下面两个PPT页面 由于第一张PPT上的内容不太准确(日志文件中没有“日志页”的概念,只有VLF的概 ...
- C语言词法分析中的贪心算法
C语言词法分析中的贪心算法 当我们写出a---b这种语句的时候我们应该考虑C语言的编译器是如何去分析这条语句的. C语言对于解决这个问题的解决方案可以归纳为一个很简单的规则:每一个符号应该包含尽可能多 ...
- 【VUE】1.搭建一个webpack项目
1.npm之类的安装跳过 2.安装npm install -g @vue/cli-init 初始化项目目录 vue init webpack vue_cutter_point_blog_admin 并 ...
- Shell编程学习(六)
Shell 脚本条件测试与比较 条件测试方法综述 在Bash的各种条件结构和控制结构中都要进行各种测试,然后根据测试结果执行不同的操作,有时也会与if等条件语句相结合,来完成测试判断,以减少程序运行的 ...
- docker redis4.0集群搭建
一.前言 redis集群对于很多人来说非常熟悉,在前些日子,我也有一位大兄弟也发布过一篇关于在阿里云(centOS7)上搭建redis 集群的文章,虽然集群搭建的文章在网上很多,我比较喜欢这篇文章的地 ...
- AGC037
Contest page A Tag:贪心 猜想段的长度只会有$1$和$2$(感性理解,应该可以反证--),然后就可以DP/贪心了 B Tag:贪心.组合 考虑如何构造合法方案.从右往左考虑球,因为当 ...