I have a HashMap<Character, Integer>
that counts the frequencies of letters in a string, called freq
. For example, if the word is PUPPY, then the map holds the values {P=3, U=1, Y=1}
.
I am using this for a wordle-like game. When assigning yellow and green to the letters of a submitted guess, I am subtracting from the frequencies of the letters, so that there are not more colors assigned than letters.
So if the target word is PUPPY and the user guesses PRUNE, then the colors work fine for the first guess but the map values become {P=2, U=0, Y=1}
. I need the frequencies to return to the original values.
I tried creating a second hashmap of the same kind and setting revert
(my second hashmap) equal to freq
, then setting freq
equal to revert
after the function is executed, but it retains its changed values.
Make a copy, modify it as you like then discard it:
Map<Character, Integer> originalFreq = ...;
while (<making guesses>) {
Map<Character, Integer> guessFreq = new HashMap<>(originalFreq); // make fresh copy
// modify guessFreq as you like - it will be discarded next loop iteration
}