Java 线性探测:插入时的ArrayIndexOutOfBoundsException
我试图在一个符号/哈希表中插入多个元素,但我不断得到一个错误ArrayIndexOutOfBoundsException,它的负数为-4923。而数组大小为10501。所以我尝试用if条件来解决这个错误,但是它看起来不起作用或者没有达到。我不确定出了什么问题Java 线性探测:插入时的ArrayIndexOutOfBoundsException,java,data-structures,Java,Data Structures,我试图在一个符号/哈希表中插入多个元素,但我不断得到一个错误ArrayIndexOutOfBoundsException,它的负数为-4923。而数组大小为10501。所以我尝试用if条件来解决这个错误,但是它看起来不起作用或者没有达到。我不确定出了什么问题 public class LinearProbing implements MultiValueSymbolTable<String, Player> { private int currentSize = 0; privat
public class LinearProbing implements MultiValueSymbolTable<String, Player> {
private int currentSize = 0;
private int capacity, collisionTotal = 0;
private String[] keys;
private Player[] values;
public LinearProbing(int arraySize) {
capacity = arraySize;
keys = new String[capacity];
values = new Player[capacity];
}
....
private int hash(String key) {
return key.hashCode() % capacity;
}
@Override
public void put(String key, Player value) {
if (key == null || value == null) {
return;
}
int hash = hash(key);
while(keys[hash] != null)
{
hash++;
hash = hash % keys.length;
collisionTotal++;
if (hash <= -1 || hash == capacity) {
hash = 0;
}
}
keys[hash] = key;
values[hash] = value;
currentSize++;
}
public类LinearProbing实现多值symboltable{
私有int currentSize=0;
专用整数容量,冲突总数=0;
私有字符串[]密钥;
个人价值观;
公用线路广播(int阵列化){
容量=阵列化;
密钥=新字符串[容量];
价值=新玩家[容量];
}
....
私有整数散列(字符串键){
return key.hashCode()%容量;
}
@凌驾
公共作废放置(字符串键、播放器值){
if(key==null | | value==null){
返回;
}
int hash=散列(键);
while(键[hash]!=null)
{
hash++;
哈希=哈希%keys.length;
collisionTotal++;
Java中的if(hash.hashCode()
可能返回负值
您可以在散列中尝试以下操作以获得非负值:
(key.hashCode() & Integer.MAX_VALUE) % capacity
hash=hash%keys。length
不应该是while循环中的hash=hash%capacity
。不要将解决方案编辑到问题中,而是发布一个答案。可以接受自答问题;在问题中放置答案不太多。尤其不要添加类似[SOLVED]的元标记
标题:这就是接受答案的意义所在。
(key.hashCode() & Integer.MAX_VALUE) % capacity