I'm trying to learn Java and got an exercise which is to get the first unique item in a string. I used HashTable as the string's characters as the key and counter of how many times it has been seen in the string as the value.
After that, I'm iterating over the HashTable and checking for each key if it has a value of 1 (only seen once) I want to return it.
The problem is, when I have a string like this for example abcdcd
a
and b
are both unique, but a
is the first one, but for some reason, when I get the keys on the HashTable, the b
comes before a
.
This is what I have:
public static Character firstNonRepeatedCharacter(String str) {
Hashtable<Character, Integer> characters = new Hashtable<Character, Integer>();
char[] charsInString = str.toCharArray();
for(int i=0; i<charsInString.length; i++){
if (characters.containsKey(charsInString[i])){
int counter = characters.get(charsInString[i]);
counter ++;
characters.put(charsInString[i], counter);
}else {
characters.put(charsInString[i], 1);
}
}
Enumeration<Character> enumeration = characters.keys();
while(enumeration.hasMoreElements()) {
Character key = enumeration.nextElement();
if(characters.get(key) == 1) {
return key;
}
}
return null;
}
Why is that happening?