[英]Rehashing method throws NullPointerException
I'm trying to do a method that automatically creates a new hashTable with 1.25 more capacity, but I have a overflow error. 我正在尝试执行一种方法,该方法会自动以1.25以上的容量创建一个新的hashTable,但出现溢出错误。 The code is: 代码是:
public void reHash (){
Config.MAX_ESTACIONS = (int) (Config.MAX_ESTACIONS * 1.25);
Vector<EstacioHash>[] newHashTable = new Vector[Config.MAX_ESTACIONS];
EstacioHash nouElement = new EstacioHash();
for (int i=0; i<hashTable.length;i++){
for (int k=0; k<hashTable[i].size();k++){
nouElement.key = hashTable[i].get(k).key;
nouElement.value = hashTable[i].get(k).value;
int position = hashFunction(nouElement.key);
newHashTable[position].add(nouElement); <---- OverFlow here
}
}
hashTable = newHashTable;
}
Why I have an overFlow? 为什么我会有流量过大? The programs run correctly without the rehash function. 没有重新哈希功能的程序可以正常运行。 The hash function is: 哈希函数是:
public int hashFunction (Object clau){
String clauMinuscules = ((String) clau).toLowerCase();
char[] key = clauMinuscules.toCharArray();
int result=0;
for (int i=0;i<key.length;i++){
result = (result + key[i]^i)%Config.MAX_ESTACIONS;
}
return result;
}
I don't think you have an overflow but more a NullPointerException
. 我认为您没有溢出,但是更多的是NullPointerException
。
The default value for an Object
is null
. Object
的默认值为null
。 When creating the new table, you have an array full of null
values. 创建新表时,您将拥有一个由null
值组成的数组。
You need to initialize each entry of the newHashTable
before trying to get the Vector
at some position and add something into it. 您需要先初始化newHashTable
每个条目, newHashTable
再尝试将Vector
放置在某个位置并将其添加到其中。
Vector<EstacioHash>[] newHashTable = new Vector[Config.MAX_ESTACIONS];
for (int i=0; i<newHashTable.length;i++){
newHashTable[i] = new Vector<EstacioHash>();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.