5

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?

BroiSatse
  • 44,031
  • 8
  • 61
  • 86
StarTrek18
  • 323
  • 4
  • 15

2 Answers2

5
HashMap<String, Integer> map = new HashMap<>();
map.put("test", 1);

I assume?

Arrem
  • 1,005
  • 9
  • 10
  • 3
    It's also worth considering a [`LinkedHashMap`](http://docs.oracle.com/javase/8/docs/api/java/util/LinkedHashMap.html) if you want to be able to iterate over your elements in insertion order. – Jeffrey Mar 29 '14 at 22:47
4

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:

  1. AbstractMap
  2. ConcurrentHashMap
  3. ConcurrentSkipListMap
  4. EnumMap
  5. HashMap
  6. Hashtable
  7. IdentityHashMap
  8. LinkedHashMap
  9. TreeMap
  10. WeakHashMap