map并不是继承Collection,map只是集合,这里Collection只是取其集合之意,游客不要误解
<span style="color:#000000;">package org.collection;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class MapDemo {
public static void main(String[] args) {
//创建一个map集合
/**
* hashMap 许使用 null 值和 null 键
* 注意,此实现不是同步的。如果多个线程同时访问一个哈希映射,而其中至少一个线程从结构上修改了该映射,则它必须 保持外部同步
* 除了非同步和允许使用 null 之外,HashMap 类与 Hashtable 大致相同
*/
Map<String,Integer> map = new HashMap<String,Integer>();
//isEmpty() 如果此映射不包含键-值映射关系,则返回 true
boolean isEmpty = map.isEmpty();
System.out.println("是否为空:"+isEmpty);
//是否为空:true
//put(K key, V value) 向map集合中添加键值对
map.put("java", 100);
map.put("php", 85);
map.put("C#", 95);
map.put("C++", 90);
System.out.println("输出 map 集合:"+map.toString());
//输出 map 集合:{C#=95, php=85, java=100, C++=90}
//size()
int size = map.size();
System.out.println("map 的长度:"+size);
//map 的长度:4
//get(Object key) 根据键获取值
int java = map.get("java");
System.out.println("jave的值:"+java);
//jave的值:100
//putAll(Map<? extends K,? extends V> m) 将指定映射的所有映射关系复制到此映射中
Map<String,Integer> map1 = new HashMap<String,Integer>();
map1.put("11", 11);
map1.put("12", 12);
map.putAll(map1);
System.out.println("输出 map 集合:"+map.toString());
//输出 map 集合:{C#=95, php=85, java=100, C++=90, 11=11, 12=12}
boolean containsKey = map.containsKey("java");
System.out.println("是否包含指定的键:"+containsKey);
//是否包含指定的键:true
boolean containsValue = map.containsValue(66);
System.out.println("是否包含指定的值:"+containsValue);
//是否包含指定的值:false
//remove(key) 从map移除指定键的映射关系(如果存在)
int a = map.remove("java");
System.out.println("移除的值:"+a);
//移除的值:100
//遍历map 遍历key
Set<String> set = map.keySet();
for( String str : set){
System.out.println(str);
}
//C# php C++ 11 12
System.out.println("-------------------");
//遍历map 遍历value
Collection<Integer> val = map.values();
for(Integer i : val){
System.out.println(i);
}
//95, 85 ,90, 11, 12
System.out.println("-------------------");
//遍历map 遍历key-value
Set<Entry<String,Integer>> entry = map.entrySet();
for(Entry<String,Integer> s : entry){
System.out.println(s.getKey()+" : "+s.getValue());
}
// C# : 95
// php : 85
// C++ : 90
// 11 : 11
// 12 : 12
}
}</span>