Map接口
-
特点:存储一对数据(Key-value),无序,无下标,键不可重复,值可重复。
-
方法:
方法 解释 V put (K key , V value ) 将对象存入集合中,关联键值。key重复则覆盖原值 Object get(Object Key) 根据键获取对应的值 Set 返回所有的key Collection values() 返回包含所有值的collection 集合 Set<Map.Entry <K,Y>> 键值匹配的Set集合 -
Map接口的特点:
- 用于存储任意键值对(Key-Value)
- 键:无序 无下标 不允许重复(唯一)
- 值:无序 无下标 允许重复
-
案例:
/* * Map接口的使用 * 特点:(1) 存储键值对 * (2) 键不能重复 * (3) 无序 * */ public class MapTest { public static void main(String[] args) { //创建集合 Map<String,String> map=new HashMap<String, String>(); //1.添加元素 map.put("name","张三"); map.put("age","12"); map.put("sex","男"); map.put("sex","女"); //如果 Key 相等 前面的键就会被覆盖 System.out.println("元素的个数:"+map.size()); System.out.println(map.toString()); //2.删除元素 // map.remove("sex"); // map.clear(); // System.out.println("元素的个数:"+map.size()); // System.out.println(map.toString()); //3.遍历集合元素 System.out.println("---------使用KeySet()方法-------------"); for (String s : map.keySet()) { System.out.println(s+":"+map.get(s)); } //EntrySet()方法 效率高于 KeySet()方法 System.out.println("---------使用EntrySet()方法-------------"); for (Map.Entry<String, String> stringStringEntry : map.entrySet()) { System.out.println(stringStringEntry.getKey()+" : "+stringStringEntry.getValue()); } //4.判断 System.out.println(map.containsKey("name")); System.out.println(map.containsValue("")); } }
2956

被折叠的 条评论
为什么被折叠?



