-2

I am trying to insert multiple elements into a symbol/hashtable, but I'm keep getting an error ArrayIndexOutOfBoundsException with negative numbers like -4923. While the array size is 10501. So I tried to resolve this error with a if condition, but it looks like it doesn't work or isn't reached. I'm not sure what goes wrong.

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

Instead of using the hashCode() function from Java I wrote my own hash function and this works now.

 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;
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
NCode
  • 1
  • 4
  • `hash = hash % keys.length` shouldn't it be `hash = hash % capacity` in while loop?. – Vikram Singh Oct 25 '18 at 11:07
  • Instead of editing the solution into you question, post an **answer**. Self-answering questions is acceptable; putting answers in your question not so much. Especially do not add meta-tags like `[SOLVED]` to your title: that is what accepting an answer is for. – Mark Rotteveel Oct 25 '18 at 13:23

1 Answers1

1

.hashCode() in Java may return negative values.

You can try the following in hash in order to get non-negative values:

(key.hashCode() & Integer.MAX_VALUE) % capacity
DB.
  • 111
  • 5