java - 字典条目数组的数据结构

标签 java

我正在 java 中寻找一种本地方式(最好)来实现一种数据结构,以将 int 作为键和一组键/值对作为值。本质上 if 是一个由索引引用的字典数组。

例如:

MyDataStructure[[Key,Value]] foo = new ...

foo.put[["hello", "world"], ["so","rocks"]]

println(foo[0].getValue("hello")) 会打印出 "world"println(foo[0].getValue( "so")) 会打印出 "rocks"

最佳答案

  • 如果你事先知道字典的数量,那么最小结构是 Map 数组:

    Map<Key,Value>[] dictonaires = new HashMap<Key,Value>[20];
    for (int i=0; i<dictionaries.length; i++) {
        dictionaries[i] = new Hashmap<Key,Value>();
    }
    
    // Any time later, refer to a dictionary by index 
    Map<Key,Value> currentDictionary = dictionaries[10];
    // Can call currentDictionar.put/get/remove to create or update/read/delete 
    // entries, but can't add/remove entire dictionaries
    
  • 但更灵活的结构是List<Map<Key,Value>> ,因为词典的数量可以动态变化。任何List会工作 - 但在你的情况下,ArrayList最适合通过索引快速访问(获取):

    List<Map<Key,Value>> dictionaryList = new ArrayList<Map<Key,Value>>();
    
    // Then add new dictionary anytime later:
    dictionaryList.add(new HashMap<Key,Value>());    
    
    // Access by index (index matches order of adding):
    Map<Key,Value> currentDictionary = dictionaryList.get(10);    
    // Can call currentDictionar.put/get/remove to create or update/read/delete 
    // entries, but can't add/remove entire dictionaries
    
    // Or even remove entire dictionary by index:
    dictionaryList.remove(10);    
    

关于java - 字典条目数组的数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16804830/

相关文章:

java - 发现以元素 'jpa:repository' 开头的无效内容

java - 在 for 循环中的操作之间交替

Java 数组窄转换规则

java - 如何使用 spring data cassandra 知道数据库中的数据是否更新

Java,显示从jar中的资源加载的chm文件

java - 如何在JSP中迭代一个对象来获取百分比?

Java模式匹配除给定列表之外的任何字符序列

java - 如何修复连接字符串包含格式错误的名称或值

Java:For循环不打印最后一次迭代

java - 找不到方法jdependMain()作为参数