Hangman with Generics

less than 1 minute read

I’m implementing a hangman game, which uses a HashMap to store a character and result of the character guess.

<pre class="prettyprint" id="java">
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>();
}
</pre>

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.

<pre class="prettyprint" id="java">
// 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()
{…}
</pre>

I want to be able to use the generic parameter type to control what is added to the list.

<pre class="prettyprint" id="java">
// 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?
}
</pre>

Categories:

Updated:

Leave a Comment