Java Equivalent to Python Dictionaries

后端 未结 4 1031
野的像风
野的像风 2020-11-27 16:03

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

相关标签:
4条回答
  • 2020-11-27 16:17

    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.

    0 讨论(0)
  • 2020-11-27 16:26

    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.

    0 讨论(0)
  • 2020-11-27 16:26

    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.

    0 讨论(0)
  • 2020-11-27 16:34

    The idea of dictionary and Map is similar. Both contain elements like

    key1:value1, key2:value2 ... and so on
    

    In Java, Map is implemented different ways like HashMap, or TreeMap etc. put(), get() operations are similar

    import java.util.HashMap;
    
    Map map = new HashMap();
    // Put elements to the map
    map.put("Ram", new Double(3434.34));
    map.put("Krishna", new Double(123.22));
    map.put("Hary", new Double(1378.00));
    //to get elements
    map.get("Krishna"); # =123.22
    map.get("Hary"); # = 1378.00 
    

    See documentation of HashMap in java8 https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html

    0 讨论(0)
提交回复
热议问题