Map(*)——映射
比较之前的集合
List
为什么使用map
<k,v>:key–value
Api–>尽量用k去操作value
put<k,v>
package com.ffyc.map;import java.util.HashMap;
import java.util.Map;/*** 映射*/
public class MapDemo {public static void main(String[] args) {Map<Integer,Integer> map = new HashMap<>();map.put(1,99);map.put(2,89);map.put(3,56);//k不能重复,重复就会覆盖。Set的底层System.out.println(map);System.out.println(map.get(2));//桶的序号System.out.println(map.containsKey(3));//3号存在吗、map.put(2,88);System.out.println(map);//改v;k是唯一的map.remove(1);//删System.out.println(map.get(1));}
}
get(k)
contains(Key)
remove(k)
size
isEmpty()
练手:力扣 001.两数之和
Map<Integer,Integer>map = new HashMap<>();//<索引>for (int i = 0; i < nums.length; i++) {int a = nums[i];int other = target-a;// boolean f = map.containsKey(other);Interger k = map.get(other);if (f){return new int[]{map.get(other),i};}else {map.put(a,i);}}return nums;}
Map的三种遍历
接口里面写了一个子接口
package com.ffyc.map;import java.util.*;public class MapDemo02 {public static void main(String[] args) {Map<String,Integer> map = new HashMap<>();map.put("a",1);map.put("b",2);map.put("j",5);//System.out.println(map.get("b"));//map.remove("j");//System.out.println(map.get("j"));System.out.println(map);//map的遍历方式System.out.println("第一种:");//1.key存入*set*Set<String> kSet = map.keySet();for (String k : kSet){System.out.println("key:"+k+";value:"+map.get(k));}System.out.println("第二种:");//2.找出所有的value,不关心keyCollection<Integer> values = map.values();for (Integer v : values){System.out.println(v);}System.out.println("第三种:");//3.既拿到key,也拿到valueSet<Map.Entry<String,Integer>>entries = map.entrySet();for (Map.Entry<String,Integer> e : entries){System.out.println(e.getKey()+":"+e.getValue());}}
}
回顾
面向对象
集合
泛型–假象
java在编译时检查,擦除后回到原始类型。
即:java泛型: 编译时检查,=》存储内存时,泛型擦除。==》回到原始类型
可以做类型检查
不写的话Raw默认对象Object啥能存。
关系图
能存一个
能存<一对>
Set也是Map,只不过只用了key而没用value。