Map: 映射集合, 键-值映射, key-value, 键值对. 键唯一, 值不唯一
HashMap. 常用
/* 常用方法:
* 1. 集合大小: .size()
* 2. 添加元素: .put(键, 值)
* 3.获取元素: .get(键) 返回 value
* 4. 获取键集: .keySet() 返回 Set类型的集合
* 5.删除元素: .remove(键) 返回 value
* 6. 清空集合: .clear()
* 7.判断是否含有指定的键: .containsKey(对象)
*/
//创建集合
Map<String, User> userMap = new HashMap<String, User>();
//添加元素
userMap.put("peter", new User(1001, "老王"));
userMap.put("john", new User(1002, "老张"));
userMap.put("smith", new User(1003, "老李"));
//修改元素
userMap.put("smith", new User(1009, "小李"));
//删除元素
// userMap.remove("smith");
// System.out.println(userMap.remove("smith"));
//判断, 是否存在
System.out.println("smith:" + userMap.containsKey("smith"));
//集合大小
System.out.println("size:" + userMap.size());
//遍历输出集合方法一:
for(String key : userMap.keySet()) {
System.out.println(key + " -- " + userMap.get(key));
}
//遍历输出集合方法二:
//Map转换成Set集合
Set<String> keySet = userMap.keySet();
//将集合对象转换成迭代器对象
Iterator<String> iterator = keySet.iterator();
//遍历迭代器
while (iterator.hasNext()) {
//获取下一个元素
String key = (String) iterator.next();
System.out.println(key + " -- " + userMap.get(key));
}
//遍历输出集合方法三:
//通过Map.entrySet()使用迭代器遍历集合
Iterator<Map.Entry<Integer, Pet>> itpet=petList.entrySet().iterator();
/*循环输出*/
while(itpet.hasNext()) {
//获取下一个元素
Map.Entry<Integer, Pet> entry=itpet.next();
System.out.println(entry.getValue());
}