<>【一起来学Java数据结构】——Map

在java的数据结构中Map是用来查找的一种数据结构。Map是一种接口。

这种查找和普通的二分查找等之类的可不一样,因为这种事动态的查找,可以在查找的过程中进行增加,删除等操作

它主要分为HashMap和TreeMap

<>Key-Value模型

HashMap最重要的特征就是Key-Value模型了

hashMap同时可以查找key和Value两个值,key唯一,所以每一个key对应一个value

<>Key模型

TreeMap就是使用的Key模型。

但是同时他会保存key和value两个值。只是它主要将key进行排序。

<>Map的方法实现

<>put()
返回值:Value 函数名:put(key,value)
例子:
Map<String,Integer> map=new HashMap<>(); Integer a=map.put("1",1); Integer b=
map.put("2",2); Integer c=map.put("3",3); Integer d=map.put("4d",null);
//value是null也是可以的
对hashMap来说,key和value都可以是null,

对TreeMap来说,只有value可以是null
//map.put(null,1);//不可以 map.put("10",null);//可以
<>get()
返回值:Value 函数名:get(key)
例子:
Integer ret=map.get("1"); System.out.println(ret);
<>getOrDefault
返回值:Value 函数名:getOrDefault(key,Default) 找到key对应的value,没找到就返回default
例子:
Integer Value1=map.getOrDefault("1",0); System.out.println(Value1);//1 Integer
Value2=map.getOrDefault("1000",0); System.out.println(Value2);//0
<>remove
返回值:value 函数值:remove(key) 删除key和对应的value值,并返回其value System.out.println(map);
Integer value=map.remove("1"); System.out.println(value); System.out.println(map
); ---------------------------------- {1=1, 2=2, 3=3} 1 {2=2, 3=3}
<>keySet和Values

keySet:
返回值:装满key的set集合 函数值:keySet() 返回一个装有key的一个set集合 Set<String> set=map.keySet();
System.out.println(set); -------------------------- [1a, 2b, 3c] 下面这种也是可以的: for
(String s: map.keySet()) { System.out.print(s+" "); }
value
for (Integer i:map.values()) { System.out.print(i+" "); } ---------------------
1 2 3
<>entrySet
返回值:Set<Map.Entry<K,V>> 函数值:entrySet 将key和value保存到Set中
例子:
Set<Map.Entry<String,Integer>> set2=map.entrySet(); for (Map.Entry<String,
Integer> map1:set2) { System.out.println(map1); } ------------------------------
- 1a=1 2b=2 3c=3
<>containsKey和containsValue
返回值 boolean 函数值: containsKey(key),constainsValue(Value) 查找是否含有Key和value,找到返回
true,没有找到返回value System.out.println(map.containsKey("1a"));//true System.out.
println(map.containsKey("4a"));//false System.out.println(map.containsValue(1));
//true System.out.println(map.containsValue(100));//false
<>hashMap和TreeMap

<>共同点

* 线程不安全
* key的值不可一样,value可以一样
<>不同点

* hashMap的key和value可以都是null,但是TreeMap的key不可以是null,value可以是null
* hashMap是根据hash值去来查找的,TreeMap是根据排序的顺序来用的
* hashMap是哈希桶,TreeMap是红黑二叉树

技术
今日推荐
PPT
阅读数 128
下载桌面版
GitHub
百度网盘(提取码:draw)
Gitee
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:ixiaoyang8@qq.com
QQ群:766591547
关注微信