import java.util.HashMap; import java.util.Map; import java.util.Set; //Map(映射)集合 <鍵,值> public class MapTest { public static void main(String[] args) { Map map = new HashMap(); //1.增長元素 map.put(101,"金庸"); map.put(102,"古龍"); map.put(103,"倪匡"); map.put(104,"蔡瀾"); System.out.println(map); System.out.println("2-------------------------"); //2.查找元素 Object m = map.get(102); System.out.println(m); System.out.println("3-------------------------"); //3.修改元素 map.replace(102,"古龍","黃霑"); System.out.println(map); System.out.println("4-------------------------"); //4.刪除元素 map.remove(104); System.out.println(map); map.remove(103,"倪匡"); System.out.println(map); System.out.println("5--------------------------"); //5.查找全部鍵和值 Object key = map.keySet(); System.out.println(key); Object value = map.values(); System.out.println(value); //6.刪除全部鍵和值 map.clear(); System.out.println(map); } }
運行結果java
{101=金庸, 102=古龍, 103=倪匡, 104=蔡瀾} 2------------------------- 古龍 3------------------------- {101=金庸, 102=黃霑, 103=倪匡, 104=蔡瀾} 4------------------------- {101=金庸, 102=黃霑, 103=倪匡} {101=金庸, 102=黃霑} 5-------------------------- [101, 102] [金庸, 黃霑] {}