Java Review - HashMap & HashSet 源码解读
2023-03-14 22:52:33 时间
文章目录
概述
- HashMap实现了Map接口,即允许放入key为null的元素,也允许插入value为null的元素;
- 除该类未实现同步外,其余跟Hashtable大致相同;
- 跟TreeMap不同,HashMap容器不保证元素顺序,根据需要该容器可能会对元素重新哈希,元素的顺序也会被重新打散,因此不同时间迭代同一个HashMap的顺序可能会不同。
- 根据对冲突的处理方式不同,哈希表有两种实现方式,一种开放地址方式(Open addressing),另一种是冲突链表方式(Separate chaining with linked lists)。Java7 HashMap采用的是冲突链表方式。
- HashSet仅仅是对HashMap做了一层包装,也就是说HashSet里面有一个HashMap(适配器模式)。
我们这里将重点分析HashMap。
构造函数
/**
* Constructs an empty <tt>HashMap</tt> with the specified initial
* capacity and load factor.
*
* @param initialCapacity the initial capacity
* @param loadFactor the load factor
* @throws IllegalArgumentException if the initial capacity is negative
* or the load factor is nonpositive
*/
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;
this.threshold = tableSizeFor(initialCapacity);
}
/**
* Constructs an empty <tt>HashMap</tt> with the specified initial
* capacity and the default load factor (0.75).
*
* @param initialCapacity the initial capacity.
* @throws IllegalArgumentException if the initial capacity is negative.
*/
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
/**
* Constructs an empty <tt>HashMap</tt> with the default initial capacity
* (16) and the default load factor (0.75).
*/
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
/**
* Constructs a new <tt>HashMap</tt> with the same mappings as the
* specified <tt>Map</tt>. The <tt>HashMap</tt> is created with
* default load factor (0.75) and an initial capacity sufficient to
* hold the mappings in the specified <tt>Map</tt>.
*
* @param m the map whose mappings are to be placed in this map
* @throws NullPointerException if the specified map is null
*/
public HashMap(Map<? extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}
相关文章
- Linux下如何配置普通用户的sudo命令权限?
- OpenHarmony 给你的输入法加点彩—星球崛起
- 剖析 Linux 内核在底层是如何工作的
- 如何高效开发相似图像搜索引擎?
- Linux Kernel 5.19 正式发布,支持龙芯 CPU架构
- Findex – 在 Linux 中搜索和启动应用程序的超快速工具
- 基于Spring接口,集成Caffeine+Redis两级缓存
- 新版Linux在M2 MacBook Air可用,Linus Torvalds发布最新内核
- Vue2剥丝抽茧-响应式系统之分支切换
- 比各种清理大师靠谱!Edge浏览器新技术大幅提速
- 谷歌 Chrome 浏览器 104 正式版发布:加快网页加载,蓝牙 API 改进
- 递归代码都可以转为非递归吗 ?
- DevEco Device Tool:HDF框架一键生成!
- HarmonyOS 实现一个滑块验证
- Linux终端居然也可以做文件浏览器?
- 什么是虚拟机,为什么它们如此有用?
- 为什么 Kubernetes 优先使用 Systemd 做为 Cgroup Driver?
- Chrome 插件开发指南
- 我是如何使用 Linux fmt 命令来格式化文本
- 如何利用迪米特法则实现“高内聚、低耦合”?