2

问题是在输出中,单词 smart 被添加了 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 }
4

1 回答 1

4

else if的问题。您正在检查!words.containsValue(y),这将检查是否有 value clever,而没有。只有astute clever. 这将导致 的执行words.put(x, words.get(x) + " " + y + " ");,并因此将 的添加clever到 的索引中smart

您的add方法只能确保单个单词的值的唯一性,而不是多个单词。

您可以通过将HashMap单词重新定义为HashMap<string, HashSet<string>>并使用该类上的方法来解决此问题;您必须更改display方法才能打印出HashSet.

于 2012-12-06T00:30:50.550 回答