-
映射(Map<K,V>)
K---键,V---值 由键得到值(唯一),键不能重复,把这一对数据(键和值)统称为键值对,一个映射是由多个键值对组成的。
为了方便操作键和值,就把键值对抽取成一个类------Map.Entry,Entry对象都是具体的键值对,一个映射可以由多个Entry兑现组成的。
遍历映射:
1、根据键来遍历
public class MapDemo1 {
public static void main(String[] args) {
//创建映射对象
Map<String,Integer> map = new HashMap<>();
//添加元素
map.put("a",1);
map.put("b",2);
map.put("c",3);
map.put("d",1);
//1、获取映射中所有的键
Set<String> set = map.keySet();
//遍历键
for (String string:set) {
//由键获取值
System.out.println(string+"="+map.get(string));
}
}
}
2、根据键值对来进行遍历
public class MapDemo2 {
public static void main(String[] args) {
//创建映射对象
Map<String,Integer> map = new HashMap<>();
//添加元素
map.put("a",1);
map.put("b",2);
map.put("c",3);
map.put("d",1);
//2、根据键值对获取对应的键值遍历
// Set<Map.Entry<String,Integer>> set = map.entrySet();
// //遍历所有键值对---遍历set集合
// for (Map.Entry<String, Integer> entry:set) {
// //每个entry就是具体的entry对象就是键值对
// System.out.println(entry.getKey()+"="+entry.getValue());
// }
for(Map.Entry<String,Integer> entry:map.entrySet()){
System.out.println(entry.getKey()+"="+entry.getValue());
}
}
}
练习:通过映射来统计一个字符串中所有字符出现的次数
public class MapDemo3 {
public static void main(String[] args) {
//通过映射来统计一个字符串中所有字符出现的次数
//键代表字符,值代表字符出现次数
Map<String,Integer> map= new HashMap<>();
String s = "dsfjaklfjkfklfdfjkweqruqcnmzc";
//遍历字符串
for (int i = 0; i < s.length(); i++) {
//获取到每个字符
//判断存入映射的字符是否已经包含
char c= s.charAt(i);
if (map.containsKey(c+"")){
//获取上一次的这个键对应的值再加1
map.put(c+"",map.get(""+c)+1);
}else{//第一次存入不包含
map.put(c+"",1);}
}
for (Map.Entry<String,Integer> entry: map.entrySet()
) {
System.out.println(entry.getKey()+"="+entry.getValue());
}
}
}
- 主要实现类:HashMap、Hashtable
- HashMap
可以允许存储null值和null键,默认初始容量为16,默认扩容是增加一倍,如果指定初始容量,指定的值在2'n~2'(n+1),那么底层真实的容量就是2’n+1 异步式线程不安全集合。
- Hashtable
不允许存储null值和null键,默认初始容量是11,默认扩容是在原来的基础上增加一倍再加一 11---22+1----46+1 ,如果指定初始容量底层真实的初始容量就是多少。 同步式线程安全集合
映射是集合吗? 不是集合但是有联系, java集合类框架(Java Collections Framwork)-----集合、映射以及相关的操作类(Collection、Collections、Map、数组、操作数组类、Comparable接口、Iterator接口。。)