Cindy Montana
Cindy Montana

Reputation: 11

HashMap containsKey() method isn't working for certain elements

The constructor takes in two arrays, and I want to put them in my HashMap but if the map already contains a word from one of the arrays, then I want to throw an exception. This works UNLESS the duplicate term is the last one in the array terms. Why is this happening?

private HashMap<String, Double> wordToWgt = new HashMap<String, Double>();
private TST t = new TST();
double maxWeight = 0.0;
private String maxWord = "";
public Autocomplete(String[] terms, double[] weights) {
    if (terms.length != weights.length) {
        throw new IllegalArgumentException();
    }
    else {
        for (int i = 0; i < terms.length; i++) {
            if (weights[i] < 0) {
                throw new IllegalArgumentException();
            }
            else if (wordToWgt.containsKey(terms[i])) {
                throw new IllegalArgumentException();
            }
            else if (weights[i] > maxWeight) {
                maxWeight = weights[i];
                maxWord = terms[i];
            }
            t.insert(terms[i], weights[i]);
            wordToWgt.put(terms[i], weights[i]);
        }
    }

// System.out.println(wordToWgt.keySet()); }

Upvotes: 0

Views: 985

Answers (1)

Stephen C
Stephen C

Reputation: 719229

I cannot see anything wrong with your code, so I'm going to suggest some alternative explanations.

You are (I guess) using the output of

 System.out.println(wordToWgt.keySet());

to tell you that there is a duplicate. However, the key set returned by keySet is a genuine set (in the context of the semantics of String.equals). Therefore there cannot be duplicates.

So what you are seeing as duplicates are ... in fact ... not duplicates at all. How is that possible?

  • There could be a leading or trailing whitespace character on one of the strings. That can be easy to miss.

  • It could be a homoglyph problem.

It could also be that your / your tool chain is not rebuilding the code properly; i.e. the code you are running may not match the source code you are looking at / editing.


P.S. The fact that you are seeing this on the last element only could be just a coincidence, or it could be an artefact of the way that the input strings are being produced.

Upvotes: 2

Related Questions