企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
[toc] # 一、map概述 map接口实现的是一组key-value<b>键值对</b>的组合。map中的每一个成员方法由一个关键字(key)和一个值(value)构成。map接口的集合中不能有重复的key出现。 另外,set接口的底层是基于hashmap实现的。<b>set中存储的值,其实就是map中的key</b>,它们是不允许重复的。 为了更好了解map,需要了解hash算法:[http://www.cnblogs.com/xiohao/p/4389672.html](http://www.cnblogs.com/xiohao/p/4389672.html) 已知的常用map实现类有:hashmap、hashtable、linkedhashmap、treemap ## 1-1 map的映射的特点 1.一个映射不能包含重复的键; 2.每个键最多只能映射一个值; 3.键(key)只允许一个空值,值(value)可以有多个空值 4.map是无序的 ## 1-2 map的API 这里需要注意的是map中添加元素用的是put方法 ![](https://img.kancloud.cn/9d/3b/9d3bb1f20c0ecfe31715160dd56f33aa_787x645.png) # 二、hashmap ## 2-1 hashmap初始化 hashmap实现了map、clonemap、serializable三个接口,并且继承自abstractmap类。 hashmap基于<b>hash数组</b>实现,若key的hash值相同则使用链表的方式进行存储。![](https://img.kancloud.cn/8f/0f/8f0f5d45b6de2eceab5f61ee826b399c_656x291.png) 新建一个hashmap时,默认的话为初试一个大小为16,负载因子为0.75的空的hashmap ~~~ /** * 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 } ~~~ ## 2-2 hashmap常用API ### get(Object key) get方法是返回指定键所映射的值,返回的是value值。 ~~~ value=hashmap.get(key);//一般在遍历循环里写 ~~~ ### keySet() 返回此映射中所包含的键(key)的 Set 视图。返回值为一个set集合 ~~~ Set<E> set = map.keySet(); ~~~ ## 2-3 遍历hashmap 1.使用for循环 ~~~ public static void main(String[] args) { Map<String, String> map = new HashMap<String, String>(); map.put("白日鼠", "白胜"); map.put("豹子头", "林冲"); map.put("小诸葛", "富安"); //1.获取一个map集合的key的set集合 Set<String> strings = map.keySet(); //2.遍历map集合,通过上一步获取的set集合遍历的key找出value for(String key:strings){ String value = map.get(key); System.out.println(key+"-->"+value); } } ~~~ 2.使用迭代器 ~~~ //1.先拿到map的所有key值 Set<String> set = map.keySet(); //2.把key值传入迭代器 Iterator<String> iterator = set.iterator(); String key; String value; while(iterator.hasNext()){ key=iterator.next(); value=map.get(key); System.out.println(key +"-->"+value); } ~~~