JDK源码研究之-----------HashMap AND HashCode
package com.bin.jdk.util; public class Person { private String id; private String name; private int age; public Person() { } public Person(String id, String name, int age) { this.id = id; this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public void info() { System.out.println("name:" + getName() + " age:" + getAge()); } public String getId() { return id; } public void setId(String id) { this.id = id; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Person person = (Person) obj; if (id == null) { if (person.getId() != null) return false; } else if (!id.equals(person.getId())) { return false; } return true; } @Override public String toString() { return "Person [id=" + id + ", name=" + name + ", age = " + age + "]"; } }
package com.bin.jdk.util; import java.util.HashMap; import java.util.Map; import com.bin.util.map.MapUtil; public class Test { public static void main(String[] args) { /** * 判断相同元素条件 * 1、首先判断hashcode返回值是否一样 * 2、如果hashcode值一样,再调用equals方法判断 */ Map<Object,Object> map = new HashMap<Object,Object>(); Person p = new Person("1","xx",10); Person p2 = new Person("1","mm",11); map.put(p, "person1"); map.put(p2, "person2"); String result = MapUtil.foreachByKey(map); System.out.println(map.size()+" "+result); //1 Person [id=1, name=xx, age = 10]:person2; id相同,因此p、p2会被认为是同一对象,值覆盖 Person p3 = new Person("2","nn",22); map.put(p3, "person3"); String result2 = MapUtil.foreachByKey(map); System.out.println(map.size()+" "+result2); //2 Person [id=2, name=nn, age = 22]:person3;Person [id=1, name=xx, age = 10]:person2; 正常加入p3 p3.setId("1"); String result3 = MapUtil.foreachByKey(map); System.out.println(map.size()+" "+result3); //2 Person [id=1, name=nn, age = 22]:person2;Person [id=1, name=xx, age = 10]:person2; 更改了引用,并没有影响原先的对象引用 map.put(p3, "person4"); String result4 = MapUtil.foreachByKey(map); System.out.println(map.size()+" "+result4); //2 Person [id=1, name=nn, age = 22]:person4;Person [id=1, name=xx, age = 10]:person4; p3.setId("2"); Person p5 = new Person("2","xxc",23); Object o = map.get(p5); System.out.println(o.toString());//person3 原先id为2的引用对象任然存在 } }
具体Hash算法可参考:http://www.ibm.com/developerworks/cn/java/j-lo-hash/