检查密钥是否存在于散列图中,其中密钥是嵌套的散列图

时间:2014-08-25 11:08:04

标签: java hashmap

我有以下HashMap:

private HashMap<HashMap<Integer,String>,ArrayList<String>> unique_schemas = new HashMap<HashMap<Integer,String>,ArrayList<String>>();

我在添加条目或打印其内容方面没有任何问题,但我不确定如何检查现有条目。

我试过了:

//create temp HashMap to check against
HashMap<Integer,String> mapkey = new HashMap<Integer,String>();
//populate it with the values to check for
mapkey.put(parentId,text);
if (unique_schemas.containsKey(mapkey.get(0))) {
    //do whatever when the entry exists
}

这不起作用,我知道这在某处是错的,但我不知所措。任何人都可以解释我的问题吗?

2 个答案:

答案 0 :(得分:3)

您应该将支票更改为:

//create temp HashMap to check against
HashMap<Integer,String> mapkey = new HashMap<Integer,String>();
//populate it with the values to check for
mapkey.put(parentId,text);
if (unique_schemas.containsKey(mapkey)) {
    //do whatever when the entry exists
}

如果你确定地图中只有一对,你也可以只为地图分配一个元素:

private HashMap<HashMap<Integer,String>,ArrayList<String>> unique_schemas = new HashMap<HashMap<Integer,String>,ArrayList<String>>(1);

答案 1 :(得分:2)

如果您的密钥属于HashMap<Integer, String>类型,则无法使用String unique_schemas.containsKey(mapkey.get(0))类型的密钥查询地图,因为mapKey.get(0)会返回字符串键0的值,如果它存在。

因此,请尝试使用unique_schemas.containsKey(mapkey),将整个地图用作关键字,如您指定的那样。

不过,我很可能会重构整个构造,因为使用地图作为关键对我来说似乎很奇怪。密钥真的可以包含id和text的多种组合吗?如果Map<KeyClass, List<String>>改为KeyClass,那将是一个问题:{/ 1}}看起来像这样:

class KeyClass {
  Integer id;
  String text;

  public int hashCode() { ... }
  public boolean equals(Object o) { ... }
}

请注意,这只是一个存根,您需要对其进行扩展,尤其是hashCode()equals()的实现。

相关问题