前言:
大家好,我是良辰丫,今天我们来学习Map相关知识 , 认识搜索树的模型 , 通过源码以及代码深入了解Map , 还在等什么,赶快与良辰一起去探索Map的海洋吧。
个人主页:良辰针不戳
所属专栏:java数据结构
励志语句:生活也许会让我们遍体鳞伤,但最终这些伤口会成为我们一辈子的财富。
期待大家三连,关注,点赞,收藏。
作者能力有限,可能也会出错,欢迎大家指正。
愿与君为伴,共探Java汪洋大海。
我们往往把搜索的数据称为关键字(Key),和关键字对应的称为值(Value),将其称之为Key-value的键值对,我们常见的模型有下面两种.
Map是一个键值对为了让大家更加深刻的认识一下Map,我们来简单分析一下它的源码.
下面是我们使用哈希Map的正确写法,只能通过子类实例化.
方法 | 说明 |
---|---|
V get(Object key) | 返回 key 对应的 value |
V getOrDefault(Object key, V defaultValue) | 返回 key 对应的 value,key 不存在,返回默认值 |
V put(K key, V value) | 设置 key 对应的 value |
V remove(Object key) | 删除 key 对应的映射关系 |
Set keySet() | 返回所有 key 的不重复集合 |
Collection values() | 返回所有 value 的可重复集合 |
Set |
返回所有的 key-value 映射关系 |
boolean containsValue(Object value) | 判断是否包含 value |
TreeMap的底层是一个红黑树 , 并且它是由SortedMap实现的,是可比较的.
public static void main(String[] args) {
Map<String,Integer> map = new TreeMap<>();
map.put("c",2);
map.put("b",2);
map.put("a",2);
System.out.println(map);
}
public static void main(String[] args) {
Map<String,Integer> map = new TreeMap<>();
map.put("c",3);
map.put("b",2);
map.put("a",1);
int a = map.get("a");
System.out.println(a);
}
在我们的表里找不到key值 , 我们可以使用getOrDefault , 找不到的时候我们可以给它一个默认值 .
public static void main(String[] args) {
Map<String,Integer> map = new TreeMap<>();
map.put("c",3);
map.put("b",2);
map.put("a",1);
Set<String> set = map.keySet();
System.out.println(set);
}
public static void main(String[] args) {
Map<String,Integer> map = new TreeMap<>();
map.put("c",3);
map.put("b",2);
map.put("a",1);
Collection<Integer> collection = map.values();
System.out.println(collection);
}
public static void main(String[] args) {
Map<String,Integer> map = new TreeMap<>();
map.put("c",3);
map.put("b",2);
map.put("a",1);
Set<Map.Entry<String,Integer>> set = map.entrySet();
System.out.println(set);
}
遍历我们的map的方式
public static void main(String[] args) {
Map<String,Integer> map = new TreeMap<>();
map.put("c",3);
map.put("b",2);
map.put("a",1);
Set<Map.Entry<String,Integer>> set = map.entrySet();
System.out.println(set);
for(Map.Entry<String,Integer> entry:set){
System.out.println(entry.getKey()+" : "+entry.getValue());
}
}
我们一般的集合遍历一定要实现迭代器Iterable , 但是我们的map是一个单独的接口 , 和Iterable没有关系