当前位置:网站首页>Map介绍
Map介绍
2022-07-02 12:00:00 【小阿飞_】
本期精彩
目录
Map接口介绍
特点:
- 键值对(key,value),键不能重复,值可以重复,每个键可以映射到最多一个值;
- 键重复则覆盖,没有继承Collection接口;
- 可以不同键指向同一Value;
- 支持用户自由绑定Key值与Value;
- 可以直接访问Key值获得对应Value
扩容:
初始容量16,负载因子0.75,扩容增量1倍
基本方法(注:实现类都可以使用这些方法!)
1、containsKey(key):在map中是否有key存在,存在返回true,反之返回false
2、putIfAbsent(key, value):先判断指定的键(key)是否存在,不存在则将键/值对插入
3、遍历:forEach((key, value)
4、放入:put(key, value)
5、通过Key取得value:get(key)
6、获取迭代器的方法:
- keySet()
- entrySet()
遍历:
首先建立一个Set集合并往里面放入Key和value
private Map<String, String> map = new HashMap<>();
@Before
public void setup() {
map.put("1", "zs");
map.put("2", "ls");
map.put("3", "ww");
map.put("4", "zl");
}
法1:先获取所有键的Set集合,再遍历(通过键获取值)
@Test
public void demo2() {
Iterator<String> it = map.keySet().iterator();
while(it.hasNext()) {
String key = it.next();
System.out.println(map.get(key));
}
}
法2:出保存键值Entry的Set,再遍历此Set即可
@Test
public void demo9() {
Iterator<Entry<String, String>> it = map.entrySet().iterator();
while(it.hasNext()) {
Entry<String, String> entry = it.next();
System.out.println(entry.getKey() + ": " + entry.getValue());
}
Map实现类介绍
HashMap
基本介绍
- 线程不安全,最常用,速度快,无序(HashMap的无序是指不会记录插入的顺序,也不会根据特定规则进行排序; 但是HashMap存值的时候会根据key的hashCode()来计算存储的位置(位置是散列的,所以说其无序),删除时是删除元素)
- 内部采用数组来存放数据
- HashMap是查询效率最高的数据结构
遍历示例
public void demo3() {
Map<String, String> map = new HashMap<>();
map.put("4", "小明");
map.put("2", "小宝");
map.put("3", "小麦");
map.put("1", "小黑");
map.put("1", "zl");
map.put("1", "小明");
Iterator<Entry<String, String>> it = map.entrySet().iterator();
while(it.hasNext()) {
Entry<String, String> next = it.next();
System.out.println(next.getKey() + " : " + next.getValue());
}
}
输出结果
基本原理
JDK8之前Table数组中的Node()处理逻辑:(紫色处为链结构)
绿色标出的部分为JDK8新增的处理逻辑,目的是在Table[i]中的Node节点数量大于8时,通过红黑树提升查找速度
原理:使用加入HashMap的key并通过一系列hash算法等来计算出这个key对应的桶位号,这个桶号就是在array数组里面的下标位置,如果这个桶中有元素了,并且超过8个,就使用数结构,低于8个就采用链表结构
这里推荐一个网站可以看到上图的动态变化过程: Data Structure Visualization
put(key,val)方法的执行过程
HashTable
线程安全,不太常用
ConcurrentHashMap
线程安全,比HashTable性能高
关于ConcurrentHashMap,还有一个值得注意的点:
在JDK8之前,ConcurrentHashMap中采用一桶一锁(默认6把锁)的分段锁结构来存储数据防止出现多线程安全问题,但是这样做效率和性能就降低了,所以JDK8之后,采用一桶一锁结合CAS(比较并替换)操作来提高性能,性能提高的原因是在CAS中采用了乐观锁,既避免了多线程安全问题(采用局部变量)又提高了性能
TreeMap
- key值按一定的顺序排序,基于红黑树,容量无限制,非线程安全,比较常用
- 添加或获取元素时性能较HashMap慢(因为需求维护内部的红黑树,用于保证key值的顺序)
- 能比较元素的大小,根据key比较(元素的自然顺序,集合中自定义的比较器也可排序)
private TreeMap<String,Student> treeMap;
@Before
public void setup() {
treeMap = new TreeMap<String,Student>(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
// 负数 0 正数
return o1.compareTo(o2);
}
});
treeMap.put("1", new Student(5, "小白"));
treeMap.put("2", new Student(3, "小黑"));
treeMap.put("3", new Student(2, "小黄"));
treeMap.put("4", new Student(4, "小明"));
treeMap.put("3", new Student(1, "小黑"));
treeMap.put("4", new Student(4, "小明"));
}
不同于HashMap的哈希映射,TreeMap实现了红黑树的结构,形成了一颗二叉树
LinkedHashMap
- 继承HashMap
- 维护了一个双向链表
- LinkedHashMap是有序的,且默认为插入顺序
- 默认情况下使用entryset获取的集合顺序是与节点的插入顺序(默认是按照插入的顺序进行排列的,最先插入的节点(即最老的节点)为head,最新插入的节点为tail)
代码示例
Map<String, String> linkedHashMap = new LinkedHashMap<>();
@Test
public void linkedHashMap() {
linkedHashMap.put("5", "嘿嘿");
linkedHashMap.put("4", "喜喜");
linkedHashMap.put("1", "哈哈");
linkedHashMap.put("3", "呵呵");
linkedHashMap.put("3", "嗨嗨");
linkedHashMap.put("4", "喜喜");
linkedHashMap.put("1", "哈哈");
Set<Entry<String, String>> set = linkedHashMap.entrySet();
Iterator<Entry<String, String>> iterator = set.iterator();
while(iterator.hasNext()) {
Entry entry = iterator.next();
String key = (String) entry.getKey();
String value = (String) entry.getValue();
System.out.println("key:" + key + ",value:" + value);
}
}
输出结果
注意:有序和无序是描述系统内部状态、客观事物内部各要素以及客观事物之间关系的范畴。有序指系统的组成元素、事物内部诸要素或事物之间的有规则的排列、组合、运动和转化,含结构有序与运动有序;无序则相反,指事物内部诸要素或事物之间、系统内部组成元素之间混乱而无规则的组合、运动和转化,含结构无序和运动无序。有序和无序是世界上存在的两种情形,二者的差异是相对的,世间没有绝对的有序和无序,在有序的事物中存在着破坏其有规则的排列或运动过程的因素,无序的事物中总是包含有有序的因素
边栏推荐
- Large top heap, small top heap and heap sequencing
- taobao. logistics. dummy. Send (no logistics delivery processing) interface, Taobao store delivery API interface, Taobao order delivery interface, Taobao R2 interface, Taobao oau2.0 interface
- Find the maximum inscribed circle of the contour
- kityformula-editor 配置字号和间距
- Mfc a dialog calls B dialog function and passes parameters
- info [email protected]: The platform “win32“ is incompatible with this module.
- 871. 最低加油次数 : 简单优先队列(堆)贪心题
- 华为面试题: 没有回文串
- qml 弹窗框架,可定制
- 学习使用php将时间戳转换为大写日期的方法代码示例
猜你喜欢
fatal: unsafe repository is owned by someone else 的解决方法
【C语音】详解指针进阶和注意点(2)
天猫商品详情接口(APP,H5端)
[Space & single cellomics] phase 1: single cell binding space transcriptome research PDAC tumor microenvironment
Tmall product details interface (APP, H5 end)
可视化搭建页面工具的前世今生
表格响应式布局小技巧
Wechat applet uses towxml to display formula
富文本编辑器添加矢量公式(MathType for TinyMCE ,可视化添加)
How does CTO help the business?
随机推荐
Base64 coding can be understood this way
Leetcode - Search 2D matrix
MFC timer usage
Full of knowledge points, how to use JMeter to generate encrypted data and write it to the database? Don't collect it quickly
一张图彻底掌握prototype、__proto__、constructor之前的关系(JS原型、原型链)
【C语言】详解指针的初阶和进阶以及注意点(1)
Record an error report, solve the experience, rely on repetition
forEach的错误用法,你都学废了吗
Sharp tool SPL for post SQL calculation
CodeCraft-22 and Codeforces Round #795 (Div. 2)D,E
Factal: Unsafe repository is owned by someone else Solution
C# 线程传参
SQL 后计算的利器 SPL
TiDB 集群最小部署的拓扑架构
Xilinx Vivado set *.svh as SystemVerilog Header
求轮廓最大内接圆
How does CTO help the business?
Dragonfly low code security tool platform development path
Have you learned the wrong usage of foreach
TiDB 软件和硬件环境建议配置