null 插入,key的位置变化,迭代操作时间,性能因素,负载因子,Comparable,加锁,迭代器修改


null 插入,key的位置变化


Hash table based implementation of the Map interface. This
implementation provides all of the optional map operations, and permits
null values and the null key. (The HashMap
class is roughly equivalent to Hashtable, except that it is
unsynchronized and permits nulls.) This class makes no guarantees as to
the order of the map; in particular, it does not guarantee that the order
will remain constant over time.

HashMap 是基于哈希表实现的 Map 接口,实现了 Map 接口的所以可选操作,并且允许 null 的键和值;

HashTable 很类似,不同点在于是非同步,是线程不安全的,并且运行 null 插入;

HashMap 是不保证插入的顺序的,先插入与后插入的 key 的角标是没有明确的先后关系的,不是先插入的 key 的角标,就一定在前或者在后, 而是完全随机的,有散列算法计算得到;

更特别的是, HashMap key 的角标,在插入到哈希表中也不是固定不变的,在扩容的时候,会进行重新散列,得到新的角标位置 ;

多说一句,刚接触的时候,看到 >>> HashMap 是基于哈希表实现的 Map 接口 <<<< 可能会蒙;


首先要明确的是,哈希表是一种数据结构,大家都可以实现它,在java里面, HashMap 就是哈希表的实现;


说人话,就是 java 里面的 HashMap 实现了 Map 接口, 在实现接口的同时,底层使用哈希思想,实现了哈希表,以达到快速确定映射关系的目的;


迭代操作时间


This implementation provides constant-time performance for the basic
operations (get and put), assuming the hash function
disperses the elements properly among the buckets. Iteration over
collection views requires time proportional to the "capacity" of the
HashMap instance (the number of buckets) plus its size (the number
of key-value mappings). Thus, it's very important not to set the initial
capacity too high (or the load factor too low) if iteration performance is
important.

HashMap 的基本操作 put get 方法,只需要花费 常数级别 的时间,如果是迭代 HashMap ,花费的时间与 HashMap 的容量和键值对的数量成 线性关系

因此,在性能很重要的情况下,不要将初始容量设置很大,或者将负载因子设置很小 ;


性能因素

An instance of HashMap has two parameters that affect its performance: initial capacity and load factor. The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created. The load factor is a measure of how full the hash table is allowed to get before its capacity is utomatically increased. When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the hash table is rehashed (that is, internal data structures are rebuilt) so that the hash table has approximately twice the number of buckets.

HashMap 的性能被两个因素左右:容量和扩容因子;

容量即哈希表最多可以存放的数据个数;

扩容因子,在知道扩容因子之前,需要先知道 HashMap 在容量不够的时候,会进行扩容,但是并不是当整个 HashMap 都满了,才进行扩容。而是在当前 HashMap 中的键值对数量,大于 扩容因子和容量的乘积 即进行扩容;因此,负载因子,可以看做是控制哈希表何时扩容的存在 ;

哈希表在扩容的时候,一边扩容到当前容量的两倍 ;


负载因子


As a general rule, the default load factor (.75) offers a good
tradeoff between time and space costs. Higher values decrease the
space overhead but increase the lookup cost (reflected in most of
the operations of the HashMap class, including
get and put). The expected number of entries in
the map and its load factor should be taken into account when
setting its initial capacity, so as to minimize the number of
rehash operations. If the initial capacity is greater than the
maximum number of entries divided by the load factor, no rehash
operations will ever occur.

负载因子的默认值是 0.75 ,作为一个准则,这个值已经很不错了,在空间与时间上取得一个很好的平衡;如果增大负载因子,空间的浪费势必减少,但是时间的开销则会增大;反之,则空间浪费的很多,频繁触发 rehash 操作,性能堪忧 ;

一般在创建 HashMap 的时候,我们需要明确我们需要放进去的元素最大个数,然后除以 0.75 ,得到初始容量的值,以将 reHash 操作减少到最少;


Comparable


If many mappings are to be stored in a HashMap
instance, creating it with a sufficiently large capacity will allow
the mappings to be stored more efficiently than letting it perform
automatic rehashing as needed to grow the table. Note that using
many keys with the same {@code hashCode()} is a sure way to slow
down performance of any hash table. To ameliorate impact, when keys
are {@link Comparable}, this class may use comparison order among
keys to help break ties.

如果有许多键值对需要插入到 HashMap 中,那么一开始初始化就设置足够大的初始容量,是很好的选择,而非选择默认的初始容量(16),让 HashMap自己进行扩容;

有一种很好的方法,来削弱 HashMap 的性能,只要满足插入到 HashMap 中的元素的 hashCode 值都是一样的;为了避免这种情况,我们最好让元素实现 Comparable 接口;


加锁


Note that this implementation is not synchronized.
If multiple threads access a hash map concurrently, and at least one o
the threads modifies the map structurally, it must be
synchronized externally. (A structural modification is any operation
that adds or deletes one or more mappings; merely changing the value
associated with a key that an instance already contains is not a
structural modification.) This is typically accomplished by
synchronizing on some object that naturally encapsulates the map.




If no such object exists, the map should be "wrapped" using the
{@link Collections#synchronizedMap Collections.synchronizedMap}
method. This is best done at creation time, to prevent accidental
unsynchronized access to the map:
Map m = Collections.synchronizedMap(new HashMap(...));

注意,这个实现不是同步的。如果多个线程同时访问一个 HashMap,并且至少有一个线程从结构上修改了 HashMap ;

修改 HashMap 是指任何增加或删除一个或多个映射的操作;如果是仅更改已经包含的键关联的值,这样不是结构修改;

如果 HashMap 包含在对象里面,那么在对象上加锁 ;

如果是直接使用 HashMap ,则使用下面的方式进行加锁:

Map m = Collections.synchronizedMap(new HashMap(...));

迭代器修改


The iterators returned by all of this class's "collection view methods"
are fail-fast: if the map is structurally modified at any time after
the iterator is created, in any way except through the iterator's own
remove method, the iterator will throw a
{@link ConcurrentModificationException}. Thus, in the face of concurrent
modification, the iterator fails quickly and cleanly, rather than risking
arbitrary, non-deterministic behavior at an undetermined time in the
future.

集合视图方法返回的迭代器是快速失败类型的(就是 HashMap 的迭代器);当 HashMap 的迭代器被创建以后,如果 HashMap 的结构被修改,除去使用迭代器自己的 remove 方法修改,则迭代器将跑出一个异常 ConcurrentModificationException

迭代器,直接抛出异常,干净而利落,而不是冒着任意风险,导致在未来一个不确定的时间发生一个不确定的行为;



Note that the fail-fast behavior of an iterator cannot be guaranteed
as it is, generally speaking, impossible to make any hard guarantees in the
presence of unsynchronized concurrent modification. Fail-fast iterators
throw on a best-effort basis.
Therefore, it would be wrong to write a program that depended on this
exception for its correctness: the fail-fast behavior of iterators
should be used only to detect bugs.

但是需要注意的是,迭代器的快速失败行为,并不是百分百有效的,只是尽最大可能的保证,在并发的时候,可能出现修改了 HashMap 但是没有抛出异常的情况,比如在迭代的时候,在最后一次迭代的时候修改 HashMap ,就不会抛出 ConcurrentModificationException 异常 ;

因此,不能依赖抛出这个异常,然后捕捉到,以便完成某种行为,这是不可取的;迭代器只会尽可能的在修改的时候,抛出这个异常,但是不是一定抛出 ;


JDK1.8 的 HashMap 源码之文件注释的更多相关文章

  1. 基于jdk1.8的HashMap源码学习笔记

    作为一种最为常用的容器,同时也是效率比较高的容器,HashMap当之无愧.所以自己这次jdk源码学习,就从HashMap开始吧,当然水平有限,有不正确的地方,欢迎指正,促进共同学习进步,就是喜欢程序员 ...

  2. JDK1.8 的 HashMap 源码之注意事项

    文章目录 链表变树 树形结构与Comparable,性能极致与降低 链表与树之间转换的阈值 英语渣靠着翻译插件,大概翻译的,难免有错误之处,注意甄别: 链表变树 This map usually ac ...

  3. JDK1.7之 HashMap 源码分析

    转载请注明出处:http://blog.csdn.net/crazy1235/article/details/75451812 类继承关系 构造函数 Entry put put putForNullK ...

  4. Java集合(七)--基于jdk1.8的HashMap源码

    HashMap在开发中经常用,面试源码方面也会经常问到,在之前也多次了解过源码,今天算是复习一下,顺便好好总结一下,包括在后面有 相关面试题.本文不会对红黑树代码由太多深入研究,特别是删除方面太复杂, ...

  5. java并发:jdk1.8中ConcurrentHashMap源码浅析

    ConcurrentHashMap是线程安全的.可以在多线程中对ConcurrentHashMap进行操作. 在jdk1.7中,使用的是锁分段技术Segment.数据结构是数组+链表. 对比jdk1. ...

  6. HashMap源码及原理

    HashMap 简介 底层数据结构分析 JDK1.8之前 JDK1.8之后 HashMap源码分析 构造方法 put方法 get方法 resize方法 HashMap常用方法测试 感谢 changfu ...

  7. HashMap源码与相关面试题

    一.哈希表 哈希表是一种可以快速定位得数据结构.哈希表可以做到平均查找.插入.删除时间是O(1),当然这是指不发生Hash碰撞得情况.而哈希表最大得缺陷就是哈希值得碰撞(collision). Has ...

  8. 详解HashMap源码解析(上)

    jdk版本:1.8 数据结构: HashMap的底层主要基于数组+链表/红黑树实现,数组优点就是查询块,HashMap通过计算hash码获取到数组的下标来查询数据.同样也可以通过hash码得到数组下标 ...

  9. 基于JDK1.8版本的hashmap源码笔记(二)

    这一篇是接着上一篇写的, 上一篇的地址是:基于JDK1.8版本的hashmap源码分析(一)     /**     * 返回boolean类型的值,当集合中包含key的键值,就返回true,否则就返 ...

随机推荐

  1. [代码审计]PHP_Bugs题目总结(2)

    写的有点多了,上一篇放在一起显得有点臃肿,就再起一篇吧~ 迷路的老铁点这里:[代码审计]PHP_Bugs题目总结(1) 0x14 intval函数四舍五入 <?php if($_GET[id]) ...

  2. 两个int类型的数据相加,有可能会出现超出int的表示范围。

    两个int类型的数据相加,有可能会出现超出int的表示范围. /* 移位运算符: <<(左移) 规律:一个操作数进行左移运算的时候,结果就是等于操作数乘以2的n次方,n就是左移 的位数. ...

  3. 消息队列Rabbit MQ 学习第一篇

    1 介绍  1.1RabbitMQ MQ全称为Message Queue,即消息队列, RabbitMQ是由erlang语言开发,基于AMQP(Advanced Message Queue 高级消息队 ...

  4. web开发学习的网站

    网易云课堂>imooc>coursera   网易云课堂 imooc.com 关于web的视频会多一些 最近要学一个付费的课程   http://www.v2ex.com/t/154242 ...

  5. SOA面向服务体系架构

    SOA概念 1.什么是SOA 面向服务的体系结构(Service-Oriented Architecture,SOA)是一个组件模型. 它将应用程序的不同功能单元(称为服务)通过这些服务之间定义良好的 ...

  6. Java垃圾回收(java GC)

    一.GC的阶段 对每个对象而言,垃圾回收分为两个阶段:finalization和reclamation. finalization: 指运行这个对象的finalize的方法. reclamation: ...

  7. mysql innodb与myisam存储文件的区别

    myisam: .frm: 存储表定义 .myd(MYData):存储数据 .MYI(MYindex):存储引擎 innodb: .frm:存储表定义 .idb:存储数据和索引,在同一个文件中

  8. [转载]运行中的DLL自升级

      最近手头有个需求:dll需要注入到某个进程常驻,该dll具备自我升级能力,当发现新的可用版本时,立即Free自己,加载新的.下面是一个实现方案: 开启一个监听线程,从网络上拉新的可用版本,下载放到 ...

  9. PPR管各种接头产品名称

    PPR管各种接头产品名称 http://ishare.iask.sina.com.cn/f/19n7gOsntbX.html

  10. 关于Android8.0 静态注册广播 行为变更的说明。

    Andorid 8.0 对广播的使用做了变更. 当广播接收器使用静态注册方式使用时,除了一些例外,这个接收器接收不到隐式广播. 注意这个“隐式”是重点. 看了网上几篇文章,对这个变更理解有误.错误的理 ...