English 中文(简体)
java 检查双巢式哈哈马草中的钥匙存在情况
原标题:java checking for key existence in double nested hashmaps
  • 时间:2012-05-24 00:14:32
  •  标签:
  • java

我有一个双巢的哈沙马( hashmap), 想要检查密钥的存在和设置新值 。 目前我正在嵌套, 如果对帐单可以检查每个级别的关键存在 。 是否有更有效的方法来编码它?

HashMap<Foo1, HashMap<Foo2, HashMap<Foo3, Double>>> my_map = new HashMap<Foo1, HashMap<Foo2, HashMap<Foo3, Double>>>();

if (my_map.containsKey(foo1key)) {

    if (my_map.get(foo1key).containsKey(foo2key)) {

        if (my_map.get(foo1key).get(foo2key).containsKey(foo3key)) {

             return my_map.get(foo1key).get(foo2key).get(foo3key);
        }
    }
}

double foo3key = getValue();

// do the above steps again to put foo3key into map.
最佳回答

最有效的方法(假设你的数值总是不中值)如下:

HashMap<Foo2, HashMap<Foo3, Double>> map2 = my_map.get(foo1Key);
if(map2!=null) {
  HashMap<Foo3, Double> map3 = map2.get(foo2Key);
  if (map3!=null) {
    Double value = map3.get(foo3Key);
    if (value!=null) {
      return (double)value;
    } else {
      // add value to map3, or whatever
    }
  }
}

这利用了下列技术:

  • If get() returns null, you know that the key does not exist (since null values are not allowed)
  • Saving the return value of the previous get for the next lookup, so that you don t need to chain gets together

这一切都有点乱 如果你经常做这种操控 那么我建议把它分解成一个单独的功能 这样你就可以做:

double value = getNestedValue(my_map,foo1Key,foo2Key,foo3Key);
问题回答

暂无回答




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签