参考:PHP数组的Hash冲突实例 http://www.laruence.com/2011/12/30/2435.html
看到这篇帖子,其实数据结构真实的存在于身边。模仿上文,弄个Java版的。
1、重写hashcode,最好(一定)要重写equals。即hashcode相同则equals返回true
import java.util.HashMap;
public class TestWorstHashMap {
private static final int testSize = 100000;
private static final int specialId = 1;
private static final String specialName = "1";
/************************************ test1 **************************************/
class BadModel {
private int id;
private String name;
public BadModel(int id, String name) {
this.id = id;
this.name = name;
}
/**
* @see java.util.HashMap.put(K, V)
*/
@Override
public boolean equals(Object obj) {
if (obj instanceof BadModel) {
return id == ((BadModel) obj).id && name.equals(((BadModel) obj).name);
}
return false;
}
@Override
public int hashCode() {
return id;
}
}
void testBadModel1() {
HashMap<BadModel, Object> map = new HashMap<BadModel, Object>();
long start = System.currentTimeMillis();
for (int i = 0; i < testSize; i++) {
BadModel model = new BadModel(specialId, "Name" + i);
map.put(model, "test" + i);
}
long end = System.currentTimeMillis();
System.out.println("BadModel the same id : " + (end - start));
}
void testBadModel2() {
HashMap<BadModel, Object> map = new HashMap<BadModel, Object>();
long start = System.currentTimeMillis();
for (int i = 0; i < testSize; i++) {
BadModel model = new BadModel(specialId, specialName);
map.put(model, "test" + i);
}
long end = System.currentTimeMillis();
System.out.println("BadModel the same id & name : " + (end - start));
}
/************************************ test2 **************************************/
class GoodModel {
private int id;
private String name;
public GoodModel(int id, String name) {
this.id = id;
this.name = name;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof GoodModel) {
return id == ((GoodModel) obj).id && name.equals(((GoodModel) obj).name);
}
return false;
}
@Override
public int hashCode() {
return id + name.hashCode();
}
}
void testGoodModel() {
HashMap<GoodModel, Object> map = new HashMap<GoodModel, Object>();
long start = System.currentTimeMillis();
for (int i = 0; i < testSize; i++) {
GoodModel model = new GoodModel(specialId, "Name" + i);
map.put(model, "test" + i);
}
long end = System.currentTimeMillis();
System.out.println("GoodModel the same id : " + (end - start));
}
public static void main(String[] args) {
TestWorstHashMap test = new TestWorstHashMap();
test.testBadModel1();
test.testBadModel2();
test.testGoodModel();
}
}
测试结果:
BadModel the same id : 141454
BadModel the same id & name : 28
GoodModel the same id : 92
![](http://dl.iteye.com/upload/attachment/614986/b44b5a68-8607-36bd-98ef-da17b7f48652.png)
1、 table为一个Entry[] 数组。
2、以<key, value>的形式存储为一个Entry。
3、相同hashcode的key,以链头插入的方式保存。
从上图看出,我们造的数据都保存在table的一个Entry的链表中了。