Say I have the function:
public Set<String> giveUp()
{
Set<String> alreadyGuessed = guessed;
guessed = new LinkedSet<String>();
//fill Guessed with possible words
anag(currentWord, "");
//Remove ones already guessed
Iterator<String> alGuessIterator = alreadyGuessed.iterator();
while (!alGuessIterator.done())
{
guessed.remove(alGuessIterator.get());
alGuessIterator.advance();
}
return guessed;
}
When I call this function and try to store it using a line like:
LinkedSet<String> notGuessed = (LinkedSet<String>)wordGame.giveUp();
Will this always be safe regardless of the internal implementation of the function above? In otherwords, could notGuessed be an ArraySet and it still maintain a perfectly safe cast? Or am I misunderstanding the point of the interface being returned and I am just supposed to have “Set notGuessed” to prevent the need for casting?
My teacher is useless on the matter of questions regarding the class, and will also immediately give me a 0 should I do any unsafe casting.
That would not be safe, since you can’t be sure of the underlying Type. If you just need to access the methods defined by the
Setinterface, then you should use:If this happens to be a
LinkedSetyour code would “work”, but if not you will get aClassCastException. If you need it to be aLinkedSetspecifically for any reason, then thegiveUp()method should return aLinkedSetexplicitly.