HashMap是java中的数据集合,在jdk1.8的实现结构是数组加红黑树,jdk1.7的结构是数组加链表。但是这种数据结构当链表的长度很长时他的查询时间复杂度就降低到 O(n),而红黑树就是一种平衡二叉树,他的查询时间复杂度是O(logn)
HashMap的基本使用
1、put方法构造键值对,插入hashmap
Map<String,String> map =new HashMap<String ,String>();
map.put("1","hahah");
map.put("2","lalala");
System.out.println(map);
结果:
2、remove(key)单次可以删除一个元素
map.remove("1");
将key为“1”的键值对从HashMap中删除
查询:
1.get方法,传入key返回value
HashMap<String,String> hashMap = new HashMap<>();
hashMap.put("1","aa");
hashMap.put("2","ss");
hashMap.put("3","dd");
System.out.println("get方法进行查询:"+hashMap.get("1"));
结果:
2、containsKey(Object key)方法,返回值为boolean,用于判断当前hashmap中是否包含key对应的key-value
HashMap<String,String> hashMap = new HashMap<>();
hashMap.put("1","aa");
hashMap.put("2","ss");
hashMap.put("3","dd");
System.out.println("判断key值:"+hashMap.containsKey("1"));
结果:
3、containsValue(Object value)方法,返回值为boolean,用于判断当前hashmap中是否包含value对应的key-value
HashMap<String,String> hashMap = new HashMap<>();
hashMap.put("1","aa");
hashMap.put("2","ss");
hashMap.put("3","dd");
System.out.println("判断value值:"+hashMap.containsValue("aa"));
结果: