s-day04-Map集合的基本使用
This commit is contained in:
@@ -0,0 +1,75 @@
|
||||
package com.inmind.map01;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/*
|
||||
Interface Map<K,V>
|
||||
参数类型
|
||||
K - 键的类型
|
||||
V - 值的类型
|
||||
常用实现类:
|
||||
HashMap LinkedHashMap TreeMap
|
||||
|
||||
常用的数据操作方法:
|
||||
- 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 Set<K> keySet(): 获取Map集合中所有的键,存储到Set集合中。
|
||||
- public Set<Map.Entry<K,V>> entrySet(): 获取到Map集合中所有的键值对对象的集合(Set集合)。
|
||||
|
||||
*/
|
||||
public class MapDemo01 {
|
||||
public static void main(String[] args) {
|
||||
//Map多态
|
||||
//创建键值为整数,值为字符串的双列集合
|
||||
Map<Integer, String> maps = new HashMap<>();
|
||||
|
||||
/*
|
||||
添加修改元素
|
||||
public V put(K key, V value): 把指定的键与指定的值添加到Map集合中
|
||||
*/
|
||||
//如果键值不存在,put就是添加
|
||||
maps.put(3, "张飞");
|
||||
maps.put(1, "刘备");
|
||||
maps.put(2, "关羽");
|
||||
//把键为2的关羽,改为关二哥
|
||||
//如果键值存在,put就是修改
|
||||
maps.put(2, "关二哥");
|
||||
maps.put(4, "赵云");
|
||||
System.out.println(maps);
|
||||
|
||||
/*
|
||||
通过键删除键值对
|
||||
public V remove(Object key): 把指定的键 所对应的键值对元素 在Map集合中删除,返回被删除元素的值。
|
||||
*/
|
||||
//把赵云删除
|
||||
String removeVal = maps.remove(4);
|
||||
System.out.println("被删除的元素是:"+removeVal);
|
||||
|
||||
System.out.println(maps);
|
||||
/*
|
||||
查询元素(键找值)
|
||||
public V get(Object key) 根据指定的键,在Map集合中获取对应的值
|
||||
*/
|
||||
String value = maps.get(2);
|
||||
System.out.println(value);
|
||||
System.out.println(maps);
|
||||
|
||||
/*
|
||||
是否包含指定的键
|
||||
public boolean containKey(Object key):判断该集合中是否有此键。
|
||||
*/
|
||||
System.out.println("3这个键是否存在:"+maps.containsKey(3));
|
||||
|
||||
/*
|
||||
是否包含指定的值
|
||||
public boolean containValue(Object value):判断该集合中是否有此键。
|
||||
*/
|
||||
System.out.println("张飞1这个值是否存在:"+maps.containsValue("张飞1"));
|
||||
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user