进阶day04-Map集合的基本使用

This commit is contained in:
2026-02-01 16:59:16 +08:00
parent 89a00fa48f
commit 221c96844b
2 changed files with 63 additions and 0 deletions

View File

@@ -0,0 +1,62 @@
package com.inmind.map01;
import java.util.HashMap;
import java.util.Map;
/*
Interface Map<K,V>
K - 键的类型
V - 值的类型
Map的常用的实现类:
HashMap LinkedHashMap
常用的数据操作方法:
- public V put(K key, V value): 把指定的键与指定的值添加到Map集合中。
- public V remove(Object key): 把指定的键 所对应的键值对元素 在Map集合中删除返回被删除元素的值。
- public V get(Object key) 根据指定的键在Map集合中获取对应的值。
- public boolean containKey(Object key):判断该集合中是否有此键。
- public boolean containsValue(Object value):判断该集合中是否有此键。
Map的特点
1.key是唯一不重复
2.value是可以重复
3.存取无序
*/
public class MapDemo01 {
public static void main(String[] args) {
//创建一个双列集合K为StringV也为String
Map<String, String> map = new HashMap<>();
//添加一对数据(增加)
map.put("刘备", "孙尚香");
map.put("吕布", "貂蝉");
map.put("董卓", "貂蝉");
System.out.println(map);
//修改董卓的对象,注意:只能修改值,不能改键(修改)
map.put("董卓", "貂蝉1");
System.out.println(map);
//根据键,删除键值对(删除)
String removedVal = map.remove("董卓");
System.out.println("被删除的键值对的值:"+ removedVal);
System.out.println(map);
//根据键,查询对应键值对的值(查询)
String getVal = map.get("刘备");
System.out.println(getVal);//孙尚香
//查询指定的双列集合,是否有对应的键值(判断)
//- public boolean containKey(Object key):判断该集合中是否有此键。
System.out.println(map.containsKey("董卓"));
System.out.println(map.containsKey("刘备"));
//- public boolean containsValue(Object value):判断该集合中是否有此键。
System.out.println(map.containsValue("孙尚香"));
System.out.println(map.containsValue("貂蝉"));
}
}