【问题标题】:What is the best datastructure to use in Java for a "multidimensional" list?在 Java 中用于“多维”列表的最佳数据结构是什么?
【发布时间】:2009-10-05 03:02:56
【问题描述】:

我需要一个类似字典的数据结构,存储信息如下:

key [value 1] [value 2] ...

我需要能够通过提供键和我想要的值来查找给定值(值的数量是恒定的)。哈希表是我首先想到的,但我认为它不能用于多个值。有没有办法使用单个数据结构来做到这一点,而不是将每个键值对拆分为单独的列表(或哈希表)?另外我宁愿不使用多维数组,因为事先不知道条目的数量。谢谢

【问题讨论】:

    标签: java list data-structures


    【解决方案1】:

    我不确定您对值列表和查找给定值的含义。这基本上是名称-值对的键控列表吗?还是要按索引指定值?

    如果是后者,您可以使用包含 ArrayLists 的 HashMap - 我假设这些值是字符串,如果键也是字符串,它看起来像这样:

    
        HashMap<String, ArrayList<String>> hkansDictionary = new HashMap<String, ArrayList<String>>();
    
        public String getValue (String key, int valueIdx) {
            ArrayList<String> valueSet = hkansDictionary.get(key);
            return valueSet.get(valueIdx);
        }
    
    

    如果是前者,您可以使用包含 HashMap 的 HashMap。看起来更像这样:

    
        HashMap<String, HashMap<String, String>> hkansDictionary 
                  = new HashMap<String, HashMap<String, String>>();
        ----
        public String getValue (String key, String name) {
            HashMap<String, String> valueSet = hkansDictionary.get(key);
                return valueSet.get(name);
        }
    

    【讨论】:

    • 谢谢..HashMaps的HashMap正是我要找的。​​span>
    【解决方案2】:

    您可以创建一个包含您要查找的两个键值的类,实现 equals() 和 hashcode() 来检查/组合对基础值的调用,并将这个新类用作 Map 的键。

    【讨论】:

      【解决方案3】:

      我会用

      Map<Key,ArrayList<String>> map = new HashMap<Key,ArrayList<String>>
      

      您将 Key 定义为的位置

      public class Key{
          private String key;
          private String value;
          //getters,setters,constructor
      
          //implement equals and hashcode and tostring
      }
      

      那你就可以了

      Key myKey = new Key("value","key");
      map.get(myKey);
      

      这将返回一个包含 N 个项目的列表

      【讨论】:

        【解决方案4】:

        你可以创建一个多维数组,首先声明它,然后创建一个方法来确保在 put 之前初始化新的值键。此示例使用带有嵌入式列表的地图,但您可以拥有地图的地图,或任何您想要的。

        也就是说,您必须定义自己的 put 方法来处理新值 initialization,如下所示:

        private static Map<String, List<USHCommandMap>> uSHCommandMaps = new HashMap<String, List<USHCommandMap>>();
        
        public void putMemory() {
        
                if (!uSHCommandMaps.containsKey(getuAtom().getUAtomTypeName()))
                    uSHCommandMaps.put(getuAtom().getUAtomTypeName(), new ArrayList<USHCommandMap>());
        
                uSHCommandMaps.get(getuAtom().getUAtomTypeName()).add(this);
        
            }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-05-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-08-13
          相关资源
          最近更新 更多