I am really used at the following kind of code in Ruby:
my_hash = {}
my_hash['test'] = 1
What is the correspondent data structure in Java?
I am really used at the following kind of code in Ruby:
my_hash = {}
my_hash['test'] = 1
What is the correspondent data structure in Java?
HashMap<String, Integer> map = new HashMap<>();
map.put("test", 1);
I assume?
In Java, there are many classes that implement the Map<K,V>
interface, which is what a Ruby "hash" is (the data structure is also commonly known as a "dictionary", or by its full name, a "hashtable"). So in Java, you can either declare an instance of the interface and assign a concrete class to it, or you can declare the concrete instance directly:
Map<String, String> definitions = new HashMap<String, String>();
definitions.put("dog", "a four-legged mammal that is Man's best friend");
definition = definitions.get("dog");
TreeMap<Integer, String> players = new TreeMap<Integer, String>();
players.put(10, "John Doe");
player = players.get(10);
This is somewhat similar to "duck-typing" in Ruby, where if an object responds to a method call X()
, then Ruby doesn't actually care what type of object that it's calling X()
on.
The following is the list of some of the classes that implement the Map<K,V>
interface: