有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java线性探测:插入时ArrayIndexOutOfBoundsException

我试图在一个符号/哈希表中插入多个元素,但我不断得到一个错误ArrayIndexOutOfBoundsException,它的负数为-4923。而数组大小为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()函数,而是编写了自己的hash函数,现在可以使用了

 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) 个答案

  1. # 1 楼答案

    Java中的.hashCode()可能返回负值

    为了获得非负值,可以在hash中尝试以下操作:

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