Java是否有一个存储键值对的数据结构,相当于C#中的IDictionary?

时间:2012-06-08 11:53:34

标签: java data-structures dictionary

  

可能重复:
  What will store a Key-Value list in Java or an alternate of C# IDictionary in Java?

在C#中有一个名为IDictionary的数据结构,它存储一组键值对。 Java中有simillar数据结构吗?如果是这样,它叫什么,谁能给我一个如何使用它的例子?

2 个答案:

答案 0 :(得分:20)

最好的方法之一是HashMap:

使用此示例:

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

请看这个链接:http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html

答案 1 :(得分:3)

您可以使用java.util.Map的各种实现(请参阅http://docs.oracle.com/javase/7/docs/api/java/util/Map.html)。类字典地图最常用的Map实现应该是HashMap。

但是,根据确切的使用方案,另一种类型的地图可能会更好。