3

Possible Duplicate:
What will store a Key-Value list in Java or an alternate of C# IDictionary in Java?

In C# there is a data structure named IDictionary which stores a collection of key-value pairs. Is there simillar data structure in Java? If so, what is it called and can anybody give me an example of how to use it?

Community
  • 1
  • 1
Conscious
  • 1,603
  • 3
  • 18
  • 16

2 Answers2

22

One of the best ways is HashMap:

Use this sample:

HashMap<String, Integer> dicCodeToIndex;
dicCodeToIndex = new HashMap<String, Integer>();

// valuating
dicCodeToIndex.put("123", 1);
dicCodeToIndex.put("456", 2);

// retrieving
int index = dicCodeToIndex.get("123");
// index is 1

Look at this link: http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html

Karen Gonzalez
  • 664
  • 9
  • 17
Bob
  • 22,810
  • 38
  • 143
  • 225
  • 6
    Any class that implements java.util.Map will do, not just HashMap. – duffymo Jun 08 '12 at 11:55
  • 2
    I would say that creating a new TreeMap or LinkedHashMap is just as simple. And if I rewrite your code properly to use the Map as the reference type on the left hand side I can change the implementation at will. – duffymo Jun 08 '12 at 12:03
3

You can use the various implementations of java.util.Map (see http://docs.oracle.com/javase/7/docs/api/java/util/Map.html). The most commonly used Map implementation for a dictionary-like map should be HashMap.

However, depending on the exact usage scenario, another type of map might be better.

Polygnome
  • 7,639
  • 2
  • 37
  • 57