使用Map儲存物件並進行操作示例
阿新 • • 發佈:2019-01-06
例子
package com.test.jhf_6_21.classwork; import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class MapTest { public static void main(String[] args) { Map<String, Object> map = new HashMap<String, Object>(); map.put("小花", new Cat("波斯貓")); map.put("旺財", new Dog("中華田園犬")); map.put("大黑", new Dog("牧羊犬")); map.put("八戒", new Pig("荷蘭豬")); /*print(map); add(map, "啊黃", new Dog("大黃狗")); print(map); remove(map, "啊黃"); print(map); change(map, "大黑", new Dog("德國牧羊犬")); print(map);*/ show(map); } // 增 static void add(Map<String, Object> map, String key, Object Pet) { map.put(key, Pet); } // 刪 static boolean remove(Map<String, Object> map, Object key) { if (map.containsKey(key)) { map.remove(key); return true; } else { return false; } } // 查 static boolean search(Map<String, Object> map, Object key) { if (map.containsKey(key)) { return true; } else { return false; } } // 改 static boolean change(Map<String, Object> map, String key, Object Pet) { if (map.containsKey(key)) { map.remove(key); map.put(key, Pet); return true; } else { return false; } } // 迭代元素 static void print(Map<String, Object> map) { System.out.println(map.keySet() + "" + map.values()); for (Object obj : map.keySet()) { System.out.print(obj + "\t"); System.out.println(map.get(obj)); } } static void show(Map<String, Object> map) { Iterator<String> it = map.keySet().iterator(); while (it.hasNext()) { Object Pet = map.get(it.next()); System.out.println(Pet); } }
}