【问题标题】:Hashtable's Value doesn't increaing哈希表值不增加
【发布时间】:2014-10-08 16:52:49
【问题描述】:

以下Java代码:

public class TestCSVDataToMap {

    public static Hashtable<String, Integer> testTable = new Hashtable<>();

    public static void main (String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new FileReader("test.csv"));
        String line;
        while ((line = reader.readLine()) != null) {
            String symbol = "0";
            if(testTable.contains(symbol)) {
                int value = testTable.get(symbol);
                value++;
                testTable.put(symbol, value);
            }
            else {
                System.out.println("dash!");
                testTable.put(symbol, 1);
            }
        }
        System.out.println(testTable);
    }
}

有输出:

dash!
dash!
dash!
dash!
{0=1}

当解析 .csv 文件时,为什么键 '0' 的值没有增长?在 testTable(a Hashtable) 中,它被初始化为 (0,1),并且值应该不断增长,因为符号总是被检测为 '0' 的键。

【问题讨论】:

  • “test.csv”的内容是什么?
  • @rgettman 你不需要,程序输出足以看出问题(解析时实际使用了哪一行?)
  • 只是多行数据,这不是问题,我只是用它来让'while'逻辑持续几次。
  • @msrd0 你是对的;我发现了问题; containscontainsKey.

标签: java hashtable


【解决方案1】:

您正在使用contains,它确定参数是否作为值存在于Hashtable 中,而不是作为键。因为没找到,你一遍遍putting 1

改用containsKey,它确定参数是否作为键存在。

if(testTable.containsKey(symbol)){

【讨论】:

    【解决方案2】:

    contains 检查 HashTable 值。在这种情况下,您要检查密钥,因此请使用containsKey

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-28
      • 2010-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多