實現Map接口的類用來存儲鍵值對 Key---Value
Map接口的實現類有HashMap和TreeMap等
Map類中存儲的鍵值對通過鍵來識別,所以鍵不能重復
通過一個對象找到另一個對象
注意:
remove ------是指從容器中移除某一鍵值對,沒有真的的刪除
Delete --------直接刪除
1 package text; 2 3 4 import java.util.HashMap; 5 import java.util.Map; 6 7 /** 8 *測試Map的基本用法 9 * **/ 10 11 public class TestMap{ 12 public static void main(String[] args){ 13 Map map= new HashMap(); 14 map.put("高崎","55"); 15 map.put("張三", new Wife("張曼玉")); 16 Wife w=(Wife) map.get("張三");//get()方法返回的是Object對象,需要轉型 17 map.remove("高崎"); 18 Boolean t = map.containsKey("張三"); 19 System.out.println(map.get("張三")); 20 System.out.println(w.name); 21 System.out.println(map.get("高崎")); 22 System.out.println(t); 23 } 24 } 25 class Wife{ 26 String name; 27 public Wife(String name){ 28 this.name=name; 29 } 30 }
運行結果:
text.Wife@6bbc4459 張曼玉 null true
還有一些常用的方法
int size()
boolean isEmpty()
putAll(Map t)
void clear()