数据结构之散列表实现
1、总结hashcode的一个很好的文章:http://blog.csdn.net/fenglibing/article/details/8905007
http://blog.csdn.net/zhouj634620500/article/details/45034409
2、实现代码:
/*
* 1、利用数组实现的表结构;
* 2、包含几大类变量: 1、 含有元素 2、键、值对 3、该位是否有Object;
* 3、hash散列值得求取;利用hashCode 1如果a.equals(b)那么a.hashCode == b.hashCode();2如果hashCode()在同一个对象上被调用两次,它应该返回的是同一个值,这表明这个对象没有被修改过。
*/
public class MyTable {
private int manyItem;
private Object[] keys;
private Object[] values;
private boolean[] hasItem;
public MyTable(int cap) {
keys = new Object[cap];
values = new Object[cap];
hasItem = new boolean[cap];
}
private int hash(Object key) {
return Math.abs(key.hashCode()) % values.length; // hashCode是object的方法,返回的是一个int类型;abs是求一个数的绝对值;
}
private int nextIndex(int i) { // i是key和value在数组中的位置;
if (i + 1 == values.length) {
return 0;
} else {
return i + 1;
}
}
private int findIndex(Object key) {
int count = 0;
int i = hash(key);
while ((count < values.length) && hasItem[i]) { //还要判断是i对应的数组是否含有元素
if (keys[i].equals(key)) {
return i;
} else {
count++;
i = nextIndex(i);
}
}
return -1;
}
private Object get(Object key) {
int index = findIndex(key);
if (index == -1)
return null;
return values[index];
}
private void put(Object key, Object value) { //插入key和value
int i = findIndex(key);
if (i != -1) {
values[i] = value;
} else if (manyItem < values.length) {
i = hash(key);
while (keys[i] != null) {
i = nextIndex(i); // 找散列值;
}
keys[i] = key;
values[i] = value;
hasItem[i] = true;
manyItem++;
} else
throw new IllegalStateException("table is full!");
}
private void remove(Object key) { //根据key删除value
int i = findIndex(key);
if (i != -1) {
values[i] = null;
keys[i] = null;
manyItem--;
}
throw new IllegalStateException("there is no value!"); //父类:IllegalComponentStateException 在不合理或不正确时间内唤醒一方法时出现的异常信息。换句话说,即 Java 环境或 Java 应用不满足请求操作。
}
private boolean isEmpty() {
return manyItem == 0;
}
private boolean contains(Object key) {
return findIndex(key) != -1;
}
private boolean hasItem(int index){
return hasItem(index);
}
private int size(){
return manyItem;
}
public void clear() {
if (manyItem != 0) {
for (int i = 0; i < values.length; i++) {
keys[i] = null;
values[i] = null;
hasItem[i] = false;
}
manyItem = 0;
}
}
public static void main(String[] args) {
MyTable table = new MyTable(3);
table.put(1, "China");
table.put(2, "American");
table.put(3, "Janpan");
System.out.println(table.get(1).toString());
System.out.println(table.get(2).toString());
System.out.println(table.get(3).toString());
table.clear();
System.out.println(table.size());
}