This week's book giveaway is in the Design forum.We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!

# Map.get(key) lookup

Archana Honnavalli
Ranch Hand
Posts: 39
Hi,
Can someone explain me.
Why using Map.get(key) is inefficient?
This will return the corresponding value of the HashMap.

Why is using entrySet efficient?
I understand Map.entrySet converts HashMap to an Iterator.
Then by giving the key we can fetch value from Iterator.

Jeff Verdegan
Bartender
Posts: 6109
6
Archana Honnavalli wrote:Hi,
Can someone explain me.
Why using Map.get(key) is inefficient?

It's not. Why do you think it is?

Why is using entrySet efficient?

Oohhhhh, so you're talking about in the context of an iteration.

Getting a value during iteration using the getValue() of the Entry from entrySet() and getting it during an iteration using get() based on the key from keySet() are both O(1). However, Entry's getValue() method will probably have fewer steps to retrieve the value than get() will, particularly if there are a lot of collisions in your map.

I still wouldn't call get() inefficient though, and in most cases, you'll never notice any difference in the context of an application's performance.

I understand Map.entrySet converts HashMap to an Iterator.

No, it doesn't "convert" it. It just provides an Iterator over the Map's entries.

Archana Honnavalli
Ranch Hand
Posts: 39

No, it doesn't "convert" it. It just provides an Iterator over the Map's entries.

Right. My bad.
It provides an Iterator over Map's entries and we can extract value from Iterator by providing the key.
Correct?

Jeff Verdegan
Bartender
Posts: 6109
6
Archana Honnavalli wrote:

No, it doesn't "convert" it. It just provides an Iterator over the Map's entries.

Right. My bad.
It provides an Iterator over Map's entries and we can extract value from Iterator by providing the key.
Correct?

"Extract the value from the Iterator by providing the key" isn't really accurate.

EntrySet provides an iterator over Set<Map.Entry>. Whether Map.Entry.getValue() provides "direct" access to the value or is just a wrapper around something like map.get(getKey()) is unspecified. So I guess I spoke too strongly when I said, "Entry's getValue() method will probably have fewer steps to retrieve the value". I should have say it may provide more direct access.