views:

339

answers:

3

I am a long time user of Python and really like the way that the dictionaries are used. They are very intuitive and easy to use. Is there a good Java equivalent to python's dictionaries? I have heard of people using hashmaps and hashtables. Could someone explain the similarities and differences of using hashtables and hashmaps versus python's dictionaries?

+2  A: 

As far as I'm aware (I don't actually use java) dictionaries are just another name for a hashmap/hashtable.

Grabbing code from http://www.fluffycat.com/Java/HashMaps/ it seems they are used in a very similar manner, with a bit of extra java boiler-plate.

Wergan
Java even has a Dictionary interface which is implemented by Hashtable. HashMap is generally preferred, though.
Michael Myers
+5  A: 

Python's dict class is an implementation of what the Python documentation informally calls "mapping types". Internally, dict is implemented using a hashtable.

Java's HashMap class is an implementation of the Map interface. Internally, HashMap is implemented using a hashtable.

There are a few minor differences in syntax, and I believe the implementations are tuned slightly differently, but overall they are completely interchangeable.

Daniel Pryden
I appreciate your answer, that is kind of what thought.
Steve
+2  A: 

One difference between the two is that dict has stricter requirements as to what data types can act as a key. Java will allow any object to work as a key -- although you should take care to ensure that the object's hashCode() method returns a unique value that reflects its internal state. Python requires keys to fit its definition of hashable, which specifies that the object's hash code should never change over its lifetime.

Tim Clemons
This is true, but it's not actually enforced by either language. Obviously in either a Java `hashCode()` method or in a Python `__hash__()` method, you should try to return a unique value that reflects internal state. In either Java or Python, if you have a mutable object, it probably shouldn't be a hashtable key, so it makes sense to throw an exception from the `hashCode()` or `__hash__()` methods.
Daniel Pryden