我不确定我的HashTable发生了什么。但是我要知道如果数组的一半以上已满,它将重新哈希并将非空值放入一个双倍大小的新数组中。但是由于某种原因,在重新哈希处理中,数组似乎恢复为原始大小,因此Im正在获取和IndexOutofBounds错误,我不确定为什么...
这是我得到的代码:
public class HashTable {
public static void main(String[] args) {
HashTable table = new HashTable(13);
table.addItem(5, table.theTable);
table.addItem(23, table.theTable);
table.addItem(17, table.theTable);
table.addItem(8,table.theTable);
table.addItem(24, table.theTable);
table.addItem(15, table.theTable);
table.addItem(2, table.theTable);
table.addItem(46, table.theTable);
table.displayTable();
}
int size;
int count;
int[] theTable;
static int EMPTY = -1;
static int DELETED = -2;
HashTable(int size) {
this.size = size;
this.count = 0;
this.theTable = new int[size];
for(int i = 0; i < size; i++) {
this.theTable[i] = EMPTY;
}
}
void addItem(int value, int[] arr) {
//Check if array is > half full
int loadSize = size/2;
if(count > loadSize) {
rehash();
}
System.out.println("Size: " + size);
System.out.println("Length " + arr.length);
int index = hasher(value);
while(arr[index] != EMPTY && arr[index] != DELETED) {
index++;
if(index >= arr.length - 1) {
index = 0;
}
}
count++;
arr[index] = value;
}//END addItem
int hasher(int value) {
return value % size;
}
void rehash() {
int[] temp = new int[size*2];
for(int i = 0; i < size*2; i++) {
temp[i] = EMPTY;
}
size = size *2;
for(int i = 0; i < theTable.length - 1; i++) {
int value = theTable[i];
if(value != EMPTY && value != DELETED) {
this.addItem(value, temp);
}
}
theTable = temp;
}
老实说,我不确定为什么会出错。但是在主测试时,一旦调用了rehash,则输出的长度和大小均为26(加倍)。但是当尝试添加46时,大小仍然是26,但是arr.length现在是13 ...