简体   繁体   中英

Accessing single values within a Map in Java

firstly apologies if this has been asked before. I've searched and can't find anything similar so fingers crossed.

Okay, what i'm trying to do is call the method of a single object within a TreeMap. I know the key values and am trying to use .get() but when i do, although it returns the object reference i can't do anything with it.

Long story short is there a way to call a method from an object within a TreeMap, without having to iterate through the whole thing in the process? I feel like i'm misunderstanding something incredibly simple but the more i look at it the more i confuse myself. I understand how to iterate through and access all the values in the map using keySets etc. but my minds drawing a blank when it comes to this particular action.

In case it makes a difference, the key's are Integers and the values are a class i've made myself. I'm trying to access the getName() method that i've made within the class for specific keys but can't seem to figure it out.

Thanks

EDIT: I'll attempt to post the code below, posting anything that may be relevant (sorry if any of it isn't)

public class Battle {

TreeMap<Integer, Enemy> enemies = new TreeMap<Integer, Enemy>();
TreeMap<Integer, Character> battleCharacters;
int enemiesAlive;
int totalXp;

public Battle(TreeMap characters, int floorNumber)
{
    createEnemies(floorNumber);
    battleCharacters = new TreeMap<Integer, Character>(characters);

    enemiesAlive = 6;
    totalXp = 0;

    for (Map.Entry<Integer, Enemy> entry : enemies.entrySet())
    {
        totalXp = totalXp + entry.getValue().getExperienceValue();
    }
}

[...]

public void battleLoop()
{
    System.out.println("Battle!");
    System.out.println("Your Party:");
    System.out.println(battleCharacters.get(1).statusReport()); //this doesn't work
    {
        //will be changed
        enemiesAlive--;
    }
}

public void battleReport()
{
    for (int key : enemies.keySet())
    {
        enemies.get(key).statusReport(); //this works
    }
}

My guess: you have a TreeMap as a raw type instead of a TreeMap<Integer, YourObjectType> . So your get method's return type is Object and you can't call your methods on that type.

What you got is your object, and you could downcast it into your class, but you should better parameterize your TreeMap appropriately.

Provided that you've correctly created the map...

TreeMap<Integer, MyObj> myMap = new TreeMap<>();
// ... add data to map
myMap.get(myKey).getName();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM