Hashtable contains()不读取char类型

时间:2015-10-14 18:42:08

标签: java char hashtable

出于某种原因,我的哈希表的contains()方法不起作用。我正在尝试创建一个哈希表,记录每个字母在单词中的找到次数。

character : # of occurrences

如果我对错误的做法有所了解,我将不胜感激。

Hashtable<Character, Integer> table = new Hashtable<Character, Integer>();
char[] array = word.toCharArray();

//inserting letters into table
for (char letter : array) {

    //letter is already in table
    if (table.contains(letter)) {
        int x = table.get(letter);
        x++;
        //overwriting with updated value
        table.put(letter, x);
    }
    //if letter is not already in table
    else {
        table.put(letter, 1);
    }
}

1 个答案:

答案 0 :(得分:5)

它是因为contains方法查找值而不是键,你必须使用containsKey()方法接收你的字符中的字符 它应该看起来像这样

更新:这个重构怎么样?

        String word ="hello";
    Hashtable<Character, Integer> table = new Hashtable<Character, Integer>();

    //inserting letters into table
    int x;
    for (char letter : word.toCharArray()) {

        //letter is already in table
        if (table.containsKey(letter)) {
            x = table.get(letter)+1;
        }
        //if letter is not already in table
        else {
            x=1;
        }
        table.put(letter, x);
    }
    System.out.println( table);