0

I always get an NullPointerException, why??? When I run debug the int i is set to -1.... But I don`t understand it because the array is getting initialized with a LinkedList and something is added.

For notice this is the test I`m running:

Dictionary<String, String> dict = new HashDictionary<>(3);
System.out.println(dict.insert("gehen", "go") == null);
System.out.println(dict.insert("gehen", "walk").equals("go"))

and this is my code:

private static final int DEF_CAPACITY = 31;
private int size = 0;
public LinkedList<Entry<K,V>>[] tab;

@SuppressWarnings("unchecked")
public HashDictionary() {
    tab = new LinkedList[DEF_CAPACITY];
    for(int i = 0; i < tab.length; i++) {
        tab[i] = new LinkedList<>();
        size++;
    }
}

@SuppressWarnings("unchecked")
public HashDictionary(int n) {
    if(isPrim(n)) {
        tab = new LinkedList[n];
        for(int i = 0; i < n; i++) {
            tab[i] = new LinkedList<>();
            size++;

        }
        return;
    }
    System.out.println("Keine Primzahl!");
    return;
}

public int h(K key) {
    int adr = key.hashCode();
    if(adr < 0)
        adr = -adr;
    return adr % tab.length;
}

@Override
public V insert(K key, V value) {
    Entry<K,V> eintrag = new Entry<>(key,value);
    if(search(key) != null) {
        V old = search(key);
        int i = tab[h(key)].indexOf(key);
        tab[h(key)].get(i).setValue(value);
        return old;
    } else {
        if(tab[h(key)] == null)
            tab[h(key)] = new LinkedList<Entry<K,V>>();
        tab[h(key)].add(eintrag);
        return null;
    }
}

@Override
public V search(K key) {
    int i = tab[h(key)].indexOf(key);
    if(i >= 0){
        return tab[h(key)].get(i).getValue();
    }
    return null;
}

Thanks for your help!

ck1993
  • 1
  • 1
  • You should really rethink your habit of performing the same action over and over again. Your `insert` method calls `search(key)` twice, if there is a mapping, which in turn does `tab[h(key)]` twice, then, `insert` also does `tab[h(key)]` twice afterwards, so your doing `tab[h(key)]` up to six times within one `insert` call. Speaking in terms of code duplication `tab[h(key)]` appears seven times in your code. But you have shown at other points that you know local variables… – Holger Apr 05 '17 at 18:58
  • By the way, `int adr = key.hashCode(); if(adr < 0) adr = -adr; …` is broken. Just check what happens if the hash code is `Integer.MIN_VALUE`. – Holger Apr 05 '17 at 19:03
  • …and what’s the point of `.indexOf(key)`? You are searching the `key` within the list where you store the `value`s. You should not be surprised that `i` is always `-1`. – Holger Apr 05 '17 at 19:06

0 Answers0