2

roomCharacters is a HashMap of keys and values (String keys and Character objects).

I need to return a Character from the collection. I have used an Iterator to simply return the first Character it finds, when the method is called.

public Character getCharacter()
{
    Iterator<HashMap.Entry<String, Character>> it = roomCharacters.entrySet().iterator();
    if (it.hasNext())
    {
        HashMap.Entry pair = (Map.Entry)it.next();
        return pair.getValue();
    }        
}

But it fails to compile:

  incompatible types: java.lang.Object cannot be converted to Character

Clearly I've misunderstood something or missed a step. Please advise and explain where I'm going wrong.

2 Answers 2

2

If you declare your pair variable with the correct type parameters, it will work, and you can get rid of the extra cast:

    HashMap.Entry<String,Character> pair = it.next();
Sign up to request clarification or add additional context in comments.

1 Comment

@AK83 please press the green checkmark if the answer was helpful.
1

You are missing the generics specification in the definition of pair. Additionally, since it is specified using generics, note that you don't need to cast when assigning its next to pair:

public Character getCharacter()
{
    Iterator<HashMap.Entry<String, Character>> it = roomCharacters.entrySet().iterator();
    if (it.hasNext())
    {
        HashMap.Entry<String, Character> pair = it.next();
        return pair.getValue();
    }        
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.