我正在创建一个哈希映射,它进行线性探测以找到键的索引。如果键已经在索引中,我希望增加它的值,而不是向新索引中添加值。
例如,如果我得到字符串"five,five,5"的字数,我的输出是five 1,five 1、five 1而不是five 3。
我想这一定是我的containsKey方法,它使用get方法来检查我的密钥是否已经在映射中。下面是我的Hashmap.java类。
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;
}
}
请参阅此示例
import java.util.*;
import java.lang.*;
import javax.swing.JOptionPane;
import java.io.*;
public class TestingTables
{
public static void main(String args[])
{
{
String s = "Any text for word word count";
String[] splitted = s.split(" ");
Map<String, Integer> hm = new HashMap<String, Integer>();
int x;
for (int i=0; i<splitted.length ; i++) {
if (hm.containsKey(splitter[i])) {
int cont = hm.get(splitter[i]);
hm.put(splitter[i], cont + 1)
} else {
hm.put(splitted[i], 1);
}
}
}
}