开发者

Java multikeymap put-method

I want to implement the put and get-methods for a multikeymap in Java with two keys pointing to a va开发者_开发问答lue. I have written the put-method like this:

public ValueType put(KeyTypeA key1, KeyTypeB key2, ValueType value) {

 HashMap<KeyTypeB, ValueType> mappi = outerMap.get(key1);
 ValueType oldvalue;
 if (mappi.containsKey(key2)) {
  oldvalue = mappi.get(key2);
 } else {
  oldvalue = null;
 }

However, when I test this method (I have initialized mappi properly as an instance of my own multikeymap-type) with

mappi.put("xxxxx", 13, "xxxxx");

I get a NullPointerException at

if (mappi.containsKey(key2)) {

What could cause the exception? In my class MultiKeyMap I initialize the multikeymap object in the constructor, so that should be ok.


If it's not homework, you could use MultiKeyMap from Apache Commons Collections, instead of redoing it from scratch.

To answer your question, I suspect the fault lays in HashMap<KeyTypeB, ValueType> mappi = outerMap.get(key1);. If key1 has no value in outerMap, then mappi will be null, causing the NullPointerException

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜