java中map插入相同的key
测试用例:
package test; import org.junit.Test; import po.Person; import java.util.HashMap; import java.util.IdentityHashMap; import java.util.Map; /** * Created by Administrator on 2015/9/16. */ public class TestMap { /** * map插入相同key问题,value会不会覆盖 */ @Test public void testMap(){ //HashMap中key的内容相同,则覆盖 Map<String,Object> map1 = new HashMap<>(); map1.put("张三",1); map1.put("张三",2); map1.put(new String("张三"),3); //根据String特性,这三条内容相同,前两条地址相同 map1.put("李四", 4); for (String s : map1.keySet()) { System.out.println(s+"======"+map1.get(s)); } /** 结果 * 张三======3 李四======4 */ System.out.println("====================================="); //IdentityHashMap中key的内存地址必须完全相同才会覆盖 Map<String,Object> map2 = new IdentityHashMap<>(); map2.put("张三",1); map2.put("张三",2); map2.put(new String("张三"),3);// map2.put("李四", 4); for (String s : map2.keySet()) { System.out.println(s+"===="+map2.get(s)); } /** * 李四====4 张三====2 张三====3 */ System.out.println("====================================="); Map<Person,Object> map3 = new IdentityHashMap<>(); map3.put(new Person("张三", 11), 1); map3.put(new Person("张三", 11), 3); map3.put(new Person("李四", 11), 4); for (Person s : map3.keySet()) { System.out.println(s.toString()+"===="+map3.get(s)); } /** * po.Person@165474cf====1 po.Person@3ff2caf4====4 po.Person@2c0cd7d====3 */ System.out.println("====================================="); Person person = new Person("张三", 11); Person person2 = new Person("张三", 11); System.out.println(person.equals(person2)); } }
package po; /** * Created by Administrator on 2015/9/16. */ public class Person { int id; String name; int age; @Override public String toString() { return "Person{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Person person = (Person) o; if (id != person.id) return false; if (age != person.age) return false; return !(name != null ? !name.equals(person.name) : person.name != null); } @Override public int hashCode() { int result = id; result = 31 * result + (name != null ? name.hashCode() : 0); result = 31 * result + age; return result; } public Person(String name,int age){ this.name=name; this.age=age; } }
关注我的公众号