为什么值重复?

时间:2012-12-06 00:28:36

标签: java string hashmap

问题出在输出中,聪明一词加了2次。你能否告诉我为什么有两次使用相同键的重复值。在此先感谢您的帮助!

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();
    }
}

输出

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

1 个答案:

答案 0 :(得分:4)

您的else if是问题所在。您正在检查!words.containsValue(y),它会检查是否存在值clever,而不是astute clever。只有words.put(x, words.get(x) + " " + y + " ");。这将导致执行clever,从而将smart添加到add的索引。

您的HashMap方法只能确保单个单词的值,而不是多个单词。

您可以通过将HashMap<string, HashSet<string>>字词重新定义为display并使用该类中的方法来解决此问题;您必须更改HashSet方法,然后打印出{{1}}的元素。

相关问题