1、HashMap的键值对
HashMap储存数据的方式是—— 键值对
package collection;
import java.util.HashMap;
public class HashMapDemo {
public static void main(String[] args) {
HashMap<String,String> dictionary = new HashMap<String,String>();
dictionary.put("a", "哈哈哈");
dictionary.put("adc", "物理英雄");
dictionary.put("apc", "魔法英雄");
dictionary.put("t", "坦克");
System.out.println(dictionary.get("a"));
}
}
2、键不能重复,值可以重复
对于HashMap而言,key是唯一的,不可以重复的。
所以,以相同的key 把不同的value插入到 Map中会导致旧元素被覆盖,只留下最后插入的元素。
不过,同一个对象可以作为值插入到map中,只要对应的key不一样
package collection;
import java.util.HashMap;
import Charactor.Hero;
public class HashMapDemo {
public static void main(String[] args) {
HashMap<String,String> dictionary = new HashMap<String,String>();
dictionary.put("a", "哈哈哈");
dictionary.put("adc", "物理英雄");
dictionary.put("apc", "魔法英雄");
dictionary.put("t", "坦克");
System.out.println(dictionary.get("a"));
HashMap<String, Hero> heroMap = new HashMap<>();
Hero hero1 = new Hero("gareen1");
Hero hero2 = new Hero("gareen2");
// key为gareen已经有value了,再以gareen作为key放入数据,会导致原英雄,被覆盖
// 不会增加新的元素到Map中
heroMap.put("gareen", hero1);
heroMap.put("gareen", hero2);
System.out.println(heroMap); //将hero1覆盖掉了
// 清空map
heroMap.clear();
// 同一个对象可以作为值插入到map中,只要对应的key不一样
heroMap.put("hero1", hero1);
heroMap.put("hero2", hero1);
System.out.println(heroMap);
}
}