Sambulo Senda
Sambulo Senda

Reputation: 1418

How to search Object stored in HashMap

I have a Question on HashMaps. How can I search and return object details from HashMap

I declared the hashmap below

private  HashMap <String,Champions> AllChampions = new HashMap<String, Champions>();

Below I declared and added a an object to the Array, And which I want to search

Champions d = new Worrier("Elblond", 200, "Sword");

AllChampions.put(b.getName(), b);

How Can I search the Object stored in Hash Map. The code I used below doesn't work

private boolean isChampion(String name)
{
    return AllChampions.containsKey(name);
}


public String getChampion(String name)
{
    if (isChampion(name))
    {
        return AllChampions.get(name).toString();
    }
    return null;
}

Upvotes: 0

Views: 1501

Answers (2)

ravi.patel
ravi.patel

Reputation: 119

One suggestion to ur last method.

public Champion getChampion(String name)
{
    if (AllChampions.containsKey(name))
    {
        return (Champion) AllChampions.get(name);
    }
    return null;
}

Upvotes: 0

Bohemian
Bohemian

Reputation: 424973

Your bug is here:

Champions d = new Worrier("Elblond", 200, "Sword");
AllChampions.put(b.getName(), b); // you are adding b, but declared d

Change it to:

AllChampions.put(d.getName(), d);

BTW, your getChampion() method adds little value: Just use AllChampions.get(name) directly.

Upvotes: 2

Related Questions