Does Java have a data structure that stores key value pairs, equivalent to IDictionary in C#?
57,429
Solution 1
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
Solution 2
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.
Author by
Conscious
Updated on July 09, 2022Comments
-
Conscious almost 2 years
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?
-
Nikhil Agrawal almost 12 yearsIts Key-Value not string-value
-
-
duffymo almost 12 yearsAny class that implements java.util.Map will do, not just HashMap.
-
duffymo almost 12 yearsI 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.
-
greendino about 2 yearsan example would be nice tho