Hashtable does not increase

The following Java code:

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

      

has an output:

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

      

Why didn't key value '0' increase when parsing .csv files? In testTable (Hashtable) it is initialized with (0,1) and the value should keep growing as the character is always defined as a key from "0".

+3


source to share


2 answers


You are using contains

that determines if the argument exists as a value in Hashtable

and not as a key. Since it is not found, you are put

ting 1

over and over.

Instead, use containsKey

which determines if the argument exists as a key.



if(testTable.containsKey(symbol)){

      

+7


source


contains

checks the value of the HashTable. In this case, you want to check the keys, so use for containsKey

.



0


source







All Articles