Ferryzijl
Ferryzijl

Reputation: 652

Removing item's from a Hashset

I'm creating a quiz game. some answers have alternative answers for example:

who's the president of Russia?

  • Vladimir Poetin
  • Poetin

here is the code:

for (HashSet<String> answer : answers) {
    for (String alternative : answer) {
        // Apply levensthein
        int distance = levensthein(givenAnswer, alternative);
        double ratio = ((double) distance) / (Math.max(alternative.length(), givenAnswer.length()));
        // 20 % error margin
        if (ratio <= 0.2) {
            // remove this set of answers, so you can't try in the same answer again
            answers.remove(answer);
            return true;
        }
    }
}

After the levensthein check the answer must be removed from the Hashset. it works for when a question doesn't have alternative anwsers.

how can I get this working? any ideas what I do wrong?

thnx!

Upvotes: 2

Views: 118

Answers (2)

Eran
Eran

Reputation: 393801

The enhanced for loop is not suitable for removing elements from the Collections you are iterating over. Use an explicit iterator instead.

Iterator<HashSet<String>> aIter = answers.iterator();
while (aIter.hasNext()) {
    HashSet<String> answer = aIter.next();
    Iterator<String> iter = answer.iterator();
    while (iter.hasNext()) {
        String alternative = iter.next();
        // Apply levensthein
        int distance = levensthein(givenAnswer, alternative);
        double ratio = ((double) distance) / (Math.max(alternative.length(), givenAnswer.length()));
        // 20 % error margin
        if (ratio <= 0.2) {
            // remove this set of answers, so you can't try in the same answer again
            aIter.remove();
            return true;
        }
    }
}

Upvotes: 4

npinti
npinti

Reputation: 52185

You should not use a for loop to go over elements and remove them, this can cause exceptions (if I am not mistaken, ConcurrentModificationException).

The HashSet provides an explicit iterator through which you can remove the elements.

for (HashSet<HashSet<String>> answer : answers) { would need to become:

Iterator<String answerIter = answers.iterator();
while(answerIter.hasNext()) {
    HashSet<string> answer = answerIter.next();
    ...
    if (ratio <= 0.2) {
        answerIter.remove();
        return true; 
    }

Upvotes: 3

Related Questions