Question

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.

Was it helpful?

Solution

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 Set interface, then you should use:

Set<String> set = wordGame.giveUp();

If this happens to be a LinkedSet your code would "work", but if not you will get a ClassCastException. If you need it to be a LinkedSet specifically for any reason, then the giveUp() method should return a LinkedSet explicitly.

OTHER TIPS

No, your cast will fail with ClasscastException unless return type is exact same as the type you are casting.

Read this post to understand why program to an interface

You would be far better served not using global fields for things that are only used locally. In this case, you should declare guessed locally, then have anag return something.

Keeping things in the correct scope is sometimes annoying, but prevents the exact sort of confusion you're dealing with here.

As far as the actual problem you asked about, have the method return a LinkedSet, then you don't have to worry about casting.

The whole idea of returning the interface reference type is that all users should be happy with the methods it provides and not worry about the underlying implementation. If you have to cast, you're doing it wrong.

No, you are returning Set and casting to LinkedSet.

If you change

Set<String> alreadyGuessed = guessed;
guessed = new LinkedSet<String>();

to

Set<String> alreadyGuessed = guessed;
guessed = new HashSet<String>();

you will have a classcastexception.

A linked set is a Set, but a set is not necessarily a linkedset. Unless you are using methods specific to Linkedset in your code,just remove the cast.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top