2

Is there anytime when using a hashmap isn't definitely the way to go? In general, it seems like hashmaps out do trees, linked lists, and the like. Is there ever a time to not use a hash?

  • I answered basically the same question here: http://stackoverflow.com/questions/20170244/why-not-use-hashing-hash-tables-for-everything/20170281. – Alex D Dec 07 '13 at 03:55
  • Hashmap should be your **last** resort, not a hammer to hit every nail with. It provide you with zero guarantees, so if it's the only solutions you can think of for solving any problem, that implies you don't know how to solve any problem. (If you did, then you'd actually solve it, which implies you'd be able to give a performance guarantee of some kind.) – user541686 Dec 07 '13 at 04:02

1 Answers1

2

If all of your object keys have the same hashCode, or you don't even have some kind of key, or you have null keys, or your algorithm or program doesn't require a hashmap. For example, how would you implement a graph with a hashmap? How about a stack? A set?

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • 1
    A graph can easily be implemented with a hash map -- hash from nodes to vectors of adjacent nodes. Sets are also easy -- hash from members of the set to a dummy value. Stacks are also easy, if somewhat pointless -- use the hash map as an "array" by hashing from numeric indices to values, and store the highest index currently used. – Alex D Dec 07 '13 at 04:04
  • 1
    @AlexD Notice I didn't say it was impossible. But as you pointed out in your [answer](http://stackoverflow.com/a/20170281/2970947), it's not a universally applicable data structure; and at least with a stack, I'm certain you'd get better performance using other implementation strategies. – Elliott Frisch Dec 07 '13 at 04:10
  • Absolutely. That's why I said using a map to implement a stack would be pointless -- the implementation would be both slower and more complex than using a vector or linked list. – Alex D Dec 07 '13 at 04:26