Search code examples
javadebuggingkeyhashtable

Inquiry: Why is this hashtable breaking on me?


I am having trouble understanding the behavior of the code I have written below. See:

Set<String> keys = hashmap.keySet();
Iterator<String> keyiterator = keys.iterator();
while(keyiterator.hasNext()) {
    out = "";
    String s = keyiterator.next();
    ArrayList<String> temp = hashmap.get(s);

    out = out + temp.get(0);
    for(int i = 1; i < temp.size(); i ++)
    {
        String s1 = temp.get(i);
        s1 = s1.replaceAll("\\[\\[", "");
        s1 = s1.replaceAll("\\]\\]", "");
        s1 = s1.trim();
        System.out.println(s1);

        ArrayList<String> temp2 = hashmap.get(s1);

        if(temp2 != null) out = out + " " + temp2.get(0);
    }
    System.out.println(out);
}

Note:

The hashmap is of form <String, ArrayList<String>>

The ArrayList has a numeric value at position 0. For example,

Key = Doc1  List = 0, Poland, Iceland, Candy
Key = Doc2  List = 1, UK, Yule
Key = Poland List = 2, Doc1, Doc2
Key = Iceland List = 3, Doc1, Poland 

Every list entry contains at least the number entry.

Problem:

This ArrayList<String> temp = hashmap.get(s); returns list for the entry. But ArrayList<String> temp2 = hashmap.get(s1);returns null for the entry. In other words, the list is empty.

Question: Simply put. Why? The list of strings once we have stripped the left and right square (see the replaceALL portion of the code above) are keynames in the hashtable. I have tried this:

ArrayList<String> temp2 = hashmap.get("poland");

where "poland" is a known document/key word for the hashtable. But it returns nothing. However, as a sanity check, if I put ArrayList<String> temp2 = hashmap.get(s); so it is looking at the key I used above once more, it can find that key value a second time just fine.

Can someone please explain to me what is going wrong? I promise to give rep to anyone who replies meaningful to my question.


Solution

  • I notice you are doing some trimming of extra characters on your ArrayList. Could it be that your key values and your ArrayList values are getting trimmed in different ways?

    For example: s1 = "Poland" but the actual key in the hashtable, that is your s, is s = " Poland " ?