package com.gongxy.demo.mapstudy;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* Map接口(字段、映射、键值对集合)
* 常用类HashMap
* 常用方法
* put(k, V) 增加或修改新键值对,修改时返回被修改的值,新增返回null
* void clear() 清空
* int size() 个数
* v remove(K) 根据键删除,返回删除的值
* v get(k) 根据键返回值
* boolean containsKey(k)
* boolean containsValue(k)
* isEmpty() 是否空集合
* 特征:
* 1、存放的时键值对,键和值都可以为null
* 2、判断两个元素(键值对)是否一样,仅判断键,不判断值
* 3、不支持随机访问
* 4、可以三种方式遍历(键,值,键值对)遍历出来是无序的
*/
public class MapTest {
public static void main(String[] args) {
mapTest();
}
static void mapTest(){
Map<Integer, String> map = new HashMap<Integer, String>();
map.put(1, "gang");//新增
map.put(2, "dan");
System.out.println(map.put(3, "yao"));//null
System.out.println(map.put(1, "hao"));//gang 返回被修改的值 存在键,修改
//map.clear();
System.out.println(map);//{1=hao, 2=dan, 3=yao}
System.out.println(map.isEmpty());//false
System.out.println(map.size());//3
System.out.println(map.get(1));//hao
//System.out.println(map.remove(3));//yao
System.out.println(map.containsKey(2));//true
System.out.println(map.containsValue("hao"));//true
//map的三种视图
//键值对视图【entry视图】最高效
Set<Map.Entry<Integer, String>> entrySet = map.entrySet();
for (Map.Entry<Integer, String> entry: entrySet) {
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
//键视图
Set<Integer> keySet = map.keySet();
for (Integer key:
keySet) {
System.out.println(key);
System.out.println(map.get(key));
}
//值视图
Collection<String> collection = map.values();
for (String s:
collection) {
System.out.println(s);
}
}
}