1、Map集合
1.1 Map
(1)双列集合 Map<K,V> 一个元素包含两个值
(2)两个泛型 键值对 类型可以不同 键唯一 键值一一对应
1.2 HashMap
(1)底层是哈希表=数组+链表/红黑树,查询速度很快
(2)HashSet集合new的是HashMap对象,但只使用了K值,所以不能存储相同元素
(3)无序,不保证存取顺序一致
(4)实现不同步,多线程,速度快
1.3 LinkedHashMap
哈希表+链表,多一条链表,保证元素有序(迭代顺序)
1.4 常用方法
V put(K key, V value);//添加元素 返回V K不存在返回null,K已存在返回被替换的V
V remove(Object key);//移除元素 返回V K不存在返回null,K存在返回被移除的V
V get(Object key);
boolean containsKey(Object key);
Set keySet();//将Map集合中所有K取出来放在一个Set集合里
Set<Map, Entry<K, V>> entrySet();
测试类
public class Demo04MapMethod {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();//多态
//put方法
String putV1 = map.put(“01”, “张三”);
System.out.println(putV1);//null K不存在返回null
String putV2 = map.put(“01”, “李四”);
System.out.println(putV2);//张三 K已存在返回被替换的V
System.out.println(map);//{01=李四} 重写了toString方法
map.put(“02”, “王五”);
map.put(“03”, “赵六”);
map.put(“04”, “赵六”);//value可以一样
//remove方法
String removeV1 = map.remove(“04”);
System.out.println(removeV1);//K存在,赵六
String removeV2 = map.remove(“05”);
System.out.println(removeV2);//K不存在,null
System.out.println(map);//{01=李四, 02=王五, 03=赵六}
Map<String, Integer> map2 = new HashMap<>();
map2.put(“张三”, 178);
map2.put(“李四”, 187);
map2.put(“王五”, 185);
System.out.println(map2);//{李四=187, 张三=178, 王五=185} 存取顺序可能不一致
Integer removeV3 = map2.remove(“李四”);
System.out.println(removeV3);//187
System.out.println(map2);//{张三=178, 王五=185}
int removeV4 = map2.remove(“张三”);//自动拆箱
System.out.println(removeV4);//178
System.out.println(map2);//{王五=185}
// int removeV5 = map2.remove(“赵四”);//会抛出异常NullPointerException 空指针 因为不能将null赋值给int类型
// System.out.println(removeV5);
// System.out.println(map2);
//get方法
Integer getV1 = map2.get(“王五”);
System.out.println(getV1);//185,K存在
Integer getV2 = map2.get(“赵四”);
System.out.println(getV2);//null,K不存在
//containsKey方法
boolean contains1 = map2.containsKey(“王五”);
System.out.println(contains1);//true
boolean contains2 = map2.containsKey(“赵四”);
System.out.println(contains2);//false
Map<String, Integer> map3 = new HashMap<>();
map3.put(“坂田银时”, 68);
map3.put(“冲田总悟”, 60);
map3.