java - HashTable - 在重新散列中间更改数组大小
问题描述
我不确定我的 HashTable 发生了什么。但是我有它,如果数组超过半满,那么它将重新散列并将非空值放入一个双倍大小的新数组中。但是由于某种原因,在重新散列中,数组似乎恢复到原始大小,所以我得到了 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;
}
老实说,我不确定为什么会出错。但是在 main 中测试时,一旦调用 rehash,就会输出长度和大小都是 26(加倍)。但是当尝试添加 46 时,大小仍然是 26,但是 arr.length 现在是 13...
解决方案
推荐阅读
- c - 交叉编译时向 C 编译器询问数据类型
- python - Scikit Learn 中的 CountVectorizer
- python - python中变量的顺序使用集合的.update方法
- javascript - 水平滚动 - 将类添加到当前视口中的活动 div
- git - 如何限制 git 存储库的存储?
- php - 使用 Eloquent 的 Laravel 联合查询
- machine-learning - 谷歌云架构:数据湖可以用于 OLTP 吗?
- ios - 通过下拉 TableView 关闭 ViewController
- api - Postman 授权 API-Key
- testing - kotlin 多平台覆盖?