From ae701490bcc1d045af5be8d393776c8c1f5449c7 Mon Sep 17 00:00:00 2001 From: xuxin <840198532@qq.com> Date: Sun, 2 Aug 2026 16:55:01 +0800 Subject: [PATCH] =?UTF-8?q?s-day04-Map=E9=9B=86=E5=90=88=E7=9A=84=E5=9F=BA?= =?UTF-8?q?=E6=9C=AC=E4=BD=BF=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- s-day04/src/com/inmind/map01/MapDemo01.java | 75 +++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 s-day04/src/com/inmind/map01/MapDemo01.java diff --git a/s-day04/src/com/inmind/map01/MapDemo01.java b/s-day04/src/com/inmind/map01/MapDemo01.java new file mode 100644 index 0000000..d583159 --- /dev/null +++ b/s-day04/src/com/inmind/map01/MapDemo01.java @@ -0,0 +1,75 @@ +package com.inmind.map01; + +import java.util.HashMap; +import java.util.Map; + +/* + Interface Map + 参数类型 + 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 keySet(): 获取Map集合中所有的键,存储到Set集合中。 +- public Set> entrySet(): 获取到Map集合中所有的键值对对象的集合(Set集合)。 + + */ +public class MapDemo01 { + public static void main(String[] args) { + //Map多态 + //创建键值为整数,值为字符串的双列集合 + Map 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")); + + } +}