Celeritas
Celeritas

Reputation: 15091

Why is the key not being found in the hashmap?

I print out the key being searched for and the keys in the map and they are there but the assignment fails. I test by populating the map with one object and itterate through and print out the keys. The key I am referencing is there so I can't see how temp is null?

    Birds temp = (Birds)hint.get(input.substring(0, input.length()-1).trim());//the last char is being dropped off on purpose
    if(temp == null)
    {
        System.out.println("failed to map key");
        Iterator entries = hint.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry thisEntry = (Map.Entry) entries.next();
            System.out.println("Key1: "+ 
                thisEntry.getKey()); //this an next line printout the same
            System.out.println("key2: "+
                input.substring(0, input.length()-1).trim());
        }
    }

I added the following lines to bird class but still the same problem

@Override public int hashCode()
    {
        return name.hashCode();
    }

@Override
public boolean equals(Object obj) {
    Bird b = (Bird)obj;
    String str = b.name;
    if(str.compareTo(this.name) == 0)
        return true;
    else
        return false;
}

Turned out white space was screwing things up and I wasn't calling trim() often enough.

Upvotes: 1

Views: 164

Answers (1)

rgettman
rgettman

Reputation: 178333

When you call substring, keep in mind that the ending index is not included in the substring.

The substring begins at the specified beginIndex and extends to the character at index endIndex - 1

In your call

input.substring(0, input.length()-1)

you are actually taking the last character off of whatever is currently in input. So, if you had a key "finch", you are inadvertently looking up the key "finc".

I don't see a reason for the substring call at all; remove it:

Birds temp = (Birds) hint.get(input.trim());

Additionally, the cast to Birds would be unnecessary if you supplied generic type parameters to your HashMap, something like this:

Map<String, Birds> hint = new HashMap<>();

Then, when calling get, you no longer need the cast:

Birds temp = hint.get(input.trim());

Upvotes: 7

Related Questions