FullCombatBeard FullCombatBeard - 1 month ago 10
Java Question

Want to iterate through hashTable keys, use keys() or keySet()?

Trying to return all numbers in the hashtable that appear an odd number of times, I've commented the bad line.

Basically I wanted the code to go through the int array and assign it to keys of the hash table, if it appeared again (even times), make boolean false, if it appeared odd number of times boolean would be true. Then I need to iterate through the keys of the hash table and return the keys that have a boolean of true.

package practice;

import java.util.*;
/*

You are given an integer array, where all numbers except for TWO numbers appear even number of times.

Q: Find out the two numbers which appear odd number of times.

*/

public class hashTable{
public static void main(String[] args){
int[] test = {2, 2, 5, 7, 4, 4};
List<Integer> solution = new ArrayList<Integer>();
Hashtable<Integer, Boolean> ht = new Hashtable<Integer, Boolean>();
Boolean check = true;
for (int item : test){
if (!ht.containsKey(item)){
check = true;
} else{
check = false;
ht.put(item, check);
}
}

for (int item : ht.keySet()){
if (ht.get(item) == true){
solution.add(item);
}
}
System.out.println("the result is");
System.out.println(solution);
}

}

Answer

You never put the item in the hashtable when it is true.

for (int item : test){
    if (!ht.containsKey(item)){
        check = true;
    } else{
        check = false;
        ht.put(item, check);
    }
    }

Should be

for (int item : test){
    if (!ht.containsKey(item)){
        check = true;
    } else{
        check = false;
    }
        ht.put(item, check);
    }