I'm implementing a hangman game, which uses a HashMap to store a character and result of the character guess.
public abstract class Guess{}
public class CorrectGuess extends Guess{}
public class FailedGuess extends Guess{}
public class Hangman {
private Map<Character,Guess> state = new HashMap<Character,Guess>();
}
I want to be able to get a list of the various correct and failed guesses, so the details can be displayed.
The nasty solution i've currently got is to use "instanceof", but i feel this misses the point of using generics.
// the calling code looks something like
void display()
{
hangmanDisplay.display(getFailedGuesses());
consoleDisplay.display(getCorrectGuesses());
}
public List<CorrectGuess> getCorrectGuesses()
{
List<CorrectGuess> list = new ArrayList<CorrectGuess>(secret.length());
for(Iterator iterator = state.values().iterator();iterator.hasNext();)
{
Guess guess = (Guess) iterator.next();
if(guess instanceof CorrectGuess)
list.add((CorrectGuess)guess);
}
return list;
}
public List<FailedGuess> getFailedGuesses()
{...}
I want to be able to use the generic parameter type to control what is added to the list.
// the calling code would then look something like
void display()
{
hangmanDisplay.display(getGuesses(new ArrayList<FailedGuess>()));
consoleDisplay.display(getGuesses(new ArrayList<CorrectGuess>());
}
/**
* get all values of generic parameter type T in the HashSet and add to the list.
*/
public void getGuesses(List<? super Guess> list)
{
state,values().iterator();
// how can i compare the type thats in the iterator.next() with the type defined by T in the input parameter?
}