I’m trying to use the hashcode of a string and the modulus the length of a array to get the index of where it should be stored for a hash table. Here is where I think I’m messing it up:
Array declaration and constructor:
private Bucket[] list;
public Hash() {
list = new Bucket[8];
}
And the actual code:
//if such a key exists already, you should replace its value
public void insert(String key, Textbook value) {
rehash();
if(list[key.hashCode()%list.length].insert(key, value)) size++;
}
//checks if the key exists
public boolean contains(String key) {
return (list[key.hashCode()%list.length] != null) ? list[key.hashCode()%list.length].contains(key) : false;
}
public void remove(String key) {
if(list[key.hashCode()%list.length].remove(key)) size --;
}
The insert and remove return null pointers and the contains method returns always returns false.
What I am doing wrong.
Thanks.
Does not allocate any
Bucketobject, it only allocates an array full withnullvalues.Thus,
list[key.hashCode()%list.length] == null(explains whycontains()returnsnull, andlist[key.hashCode()%list.length].remove(...)orlist[key.hashCode()%list.length].insert(...)causes you to try and accessnull, which in its turn causes NPE).You will also have to iterate the array and initialize every element with non null value, using
Bucket‘s constructor or some factory method.