线性探测:插入时出现ArrayIndexOutOfBoundsException

时间:2018-10-25 11:01:12

标签: java data-structures

我试图在一个符号/哈希表中插入多个元素,但是我不断收到带有负数(如-4923)的错误ArrayIndexOutOfBoundsException。虽然数组大小为10501。所以我尝试使用if条件解决此错误,但看起来它不起作用或未达到。我不确定出什么问题。

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++;
}

我没有使用Java中的hashCode()函数,而是编写了自己的哈希函数,并且现在可以使用。

 private int hash(String key) {

    char[] s = new char[key.length()];
    int hash = 0;
    for (int i = 0; i < key.length(); i++) {
        hash = s[i] + (capacity * hash);
    }

    return hash;
}

1 个答案:

答案 0 :(得分:1)

Java中的

.hashCode()可能返回负值。

您可以在hash中尝试以下操作,以获取非负值:

(key.hashCode() & Integer.MAX_VALUE) % capacity