user1405298
user1405298

Reputation:

why does the values repeat?

The problem is in the output the word clever is added 2 times. Can you please tell me why duplicate values with the same key are being added twice. Thanks in advance for your help!

package HashMap;

import java.util.HashMap;
import java.util.Set;

public class Thesaurus {
    HashMap<String, String> words =new HashMap<String, String>();

    public void add(String x,String y)
    {
        if (!words.containsKey(x))
            words.put(x, y);
        else if (!words.containsValue(y))
            words.put(x, words.get(x) + " " + y + " ");
    }
    public void display()
    {
        System.out.println(words);
    }
    public static void main(String[] args) {
        Thesaurus tc = new Thesaurus();
        tc.add("large", "big");
        tc.add("large", "humoungus");
        tc.add("large", "bulky");
        tc.add("large", "broad");
        tc.add("large", "heavy");
        tc.add("smart", "astute");
        tc.add("smart", "clever");
        tc.add("smart", "clever");

        tc.display();
    }
}

output

{smart=astute clever  clever , large=big humoungus  bulky  broad  heavy }

Upvotes: 2

Views: 54

Answers (1)

Femaref
Femaref

Reputation: 61437

Your else if is the problem. You are checking for !words.containsValue(y), which will check if there is a value clever, which there isn't. There only is astute clever. That will cause an execution of words.put(x, words.get(x) + " " + y + " ");, and consequently, adding of clever to the index of smart.

Your add method can only assure the uniquess of values for single words, not multiple.

You can solve this by redefining your HashMap words as HashMap<string, HashSet<string>> and using the methods on that class; you'll have to change your display method though to print out the elements of the HashSet.

Upvotes: 4

Related Questions