public ststic void main(String[] arges) { Map<String,String> map = new HashMap<String,String>(); map.put("01","zhangsan");//(添加) return null map.put("01","lisi"); //(修改) 注意:键值已经存在,返回的是修改前的值 return 'zhangsan' System.out.println(map.get("01")); //(获取) return 'lisi'; System.out.println(map.get("08")); //(获取)如果不存在 return null; System.out.println(map.remove("01"));//(删除) return 'lisi'; System.out.println(map.remove("08"));//(删除)如果不存在 return null; map.put("02","wangwu"); map.put("03","zhaoliu"); map.put("04",null); //是允许的 map.put(null,"aaa");//是允许的 Collection<String> coll = map.values(); //返回集合中所有的值 System.out.println(coll); //[aaa, wangwu, zhaoliu, null] System.out.println(map);//无序 {null=aaa, 02=wangwu, 03=zhaoliu, 04=null}
Set<String> keySet = map.keySet();//获取map集合中 所有键的Set集合 Iterator<String> it = keySet.iterator(); //迭代器 while(it.hasNext()){ String key = it.next(); System.out.println(key);//打印键值 System.out.println(map.get(key));//打印键值
Set<Map.Entry<String, String>> entrySet = map.entrySet(); //也返回一个set节 Iterator<Map.Entry<String,String>> it1 = entrySet.iterator(); //迭代器 while(it1.hasNext()){ Map.Entry<String, String> me1 = it1.next(); String key1 = me1.getKey(); //直接取键值 String value1 = me1.getValue();//直接取值 }
}