Почему моя хэш-карта не возвращает количество слов?

Я создаю хэш-карту, которая выполняет линейное зондирование, чтобы найти индекс для ключа. Если ключ уже находится в индексе, я хочу увеличить его значение, а не добавлять его в новый индекс.

Например, если я получаю количество слов для строки «пять, пять, пять», я вывожу пять 1, пять 1, пять 1 вместо пяти 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;
        }

     }

person Subwoofer    schedule 27.11.2018    source источник


Ответы (1)


Ссылка на этот пример

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);
         }
      }
   }
}
person Sushant    schedule 06.12.2018