I am creating a hashmap that does linear probing to find an index for the key. If the key is already in the index, I want to increase its value, not add one to a new index.
For example, if I get a word count for the string "five, five, five" my output is five 1, five 1, five 1, instead of five 3.
I think it must be my containsKey method which uses the get method to check if my key is already in the map. Below is my Hashmap.java class.
import java.util.Hashtable;
import java.util.ArrayList;
import java.lang.Object;
public class Hashmap<K,V> implements MapSet<K,V>
{
private Object hashMap[]; //hash table
private int capacity; // capacity == table.length
private int collisions; // number of collisions
private int numItems; // number of hash table entries
public Hashmap(int arrayCapacity){
capacity = arrayCapacity;
hashMap = new Object[capacity];
collisions = 0;
numItems = 0;
}
//Returns true if the map contains a key-value pair with the given key
@SuppressWarnings({"unchecked"})
public boolean containsKey( K key ){
return get(key) != null;
}
@SuppressWarnings({"unchecked"})
public V put(K key, V value){
int hash = Math.abs(key.hashCode());
int index = hash% hashMap.length; //getting a new index for the key-value-pair
KeyValuePair<K,V> pair = (KeyValuePair<K,V>) hashMap[index];
while(pair != null && !pair.getKey().equals(key)){
index = (index+1)% hashMap.length;
pair = (KeyValuePair<K,V>)hashMap[index];
collisions++;
}
if (pair == null){
//a null spot has been found, the key value pair will be added here.
KeyValuePair<K,V> temp = new KeyValuePair<K,V>(key,value);
hashMap[index] = temp;
numItems++;
if (numItems > hashMap.length / 2) {
ensureCapacity();
}
return value;
}
else {
//the key is the same as one already in the hashmap.
//sets the value of the new key to the old key.
V oldValue = pair.getValue();
pair.setValue(value);
return oldValue;
}
}
@SuppressWarnings({"unchecked"})
public V get(K key){
int hash = Math.abs(key.hashCode());
int index = hash% hashMap.length;
KeyValuePair<K,V> pair = (KeyValuePair<K,V>) hashMap[index];
if(pair == null){
return null;
}
else if(pair.getKey() == key){
return pair.getValue();
}
else{
index = (index + 1)% hashMap.length;
int progress = 0;
while(hashMap[index] != null){
progress++;
KeyValuePair<K,V> item = (KeyValuePair<K,V>) hashMap[index];
if(item.getKey().equals(key))
return item.getValue();
if (progress == hashMap.length)
break;
}
return null;
}
}
Refer this example