赞
踩
1.Map和Set是一种专门用来进行搜索的容器/数据结构,搜索的效率和具体实例化的子类有关。
分别实例化TreeMap、HashMap,两者存在效率上的差别。
Map<String,Integer>map1 =new TreeMap<>();//查找的复杂度为o(logN) Map<String,Integer>map2 =new HashMap<>();//查找的复杂度为o(1) // TreeMap的底层是搜索树 // HashMap的底层是哈希表:数组+链表+红黑树组成
- 1
- 2
- 3
- 4
2.常见的搜索方法为 静态查找,一般不进行插入、删除。
1,直接遍历: 时间复杂度为 o(N),元素越多,效率越慢。
2.二分查找:时间复杂度为 o(log2N),要求搜索前必须是有序的。
3.而Map和Set是可以进行 动态查找 的集合容器。
4.只有关键字的叫纯Key模型(Set),由关键字和其对应的值形成的键值对,叫Key-Value模型(Map)
设置Key对应的Value,将元素对应的值进行存储
public static void main(String[] args) {
Map<String,Integer>map1 =new TreeMap<>();//查找的复杂度为o(logN)
map1.put("Math",3);
map1.put("Chinese",2);
map1.put("English",4);
System.out.println(map1);
}
//{Chinese=2, English=4, Math=3}
System.out.println(map1.get("Math"));//2
System.out.println(map1.get("Art"));//null
如果get传进的Key不存在,则返回的Value值为null
返回 key 对应的 value,key 不存在,返回默认值
map1.put("Math",3);
System.out.println(map1.getOrDefault("Science", 7));//7
System.out.println(map1.getOrDefault("Math", 7)); //3
如果给的Key值在Map中存在,返回原本的Value,忽视自己填的默认值
System.out.println(map1.remove("English"));//4
System.out.println("++++++");
System.out.println(map1.containsValue(4)); //false
System.out.println(map1.containsKey("English"));//false
再remove()中传入Key, key和其对应的Value均删除
remove()返回删除的Value
Set<String>set = map1.keySet();
System.out.println(set);//[Chinese, English, Math]
Collection<Integer> values = map1.values();
System.out.println(values);//[2, 4, 3]
返回所有的 key-value 映射关系
将map的Key和Value看作一个整体(Entry),Set中存放不同的Entry
Set<Map.Entry<String, Integer>> entrySet = map1.entrySet();
for (Map.Entry<String, Integer> entry : entrySet) {
System.out.println("Key:"+entry.getKey()+" Value:"+entry.getValue());
}
//Key:Chinese Value:2
//Key:English Value:4
//Key:Math Value:3
System.out.println(map1.containsKey("Chinese"));//true
System.out.println(map1.containsValue(3));true
map1.put("English", 4); map1.put("English",44);
- 1
- 2
如果存储相同的Key,会覆盖掉之前的Value.
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。