0

I have the following HashMap:

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

I am having no problems adding entries to it or printing out its contents but I'm not sure how to check for an existing entry.

I have tried:

//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 } 

This isn't working, I know it's wrong somewhere but I'm at a loss. Can anyone shed some light on my problem?

3
  • what's not working? how does it behave? Commented Aug 25, 2014 at 11:11
  • 4
    unique_schemas key is a HashMap<Integer,String>, and you are comparing it between mapkey.get(0) which is a String. Commented Aug 25, 2014 at 11:12
  • @bigdestroyer that makes sense, I'm not sure how the syntax of the comparison should be written. Commented Aug 25, 2014 at 11:13

2 Answers 2

3

You should change the check to:

//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 } 

If you are sure that there is just one pair in the map you could also allocate just 1 element to the map:

private HashMap<HashMap<Integer,String>,ArrayList<String>> unique_schemas = new HashMap<HashMap<Integer,String>,ArrayList<String>>(1); 
Sign up to request clarification or add additional context in comments.

1 Comment

Ah so simple, I was running around in circles! Thanks alot!
2

If your key is of type HashMap<Integer, String> you can't query the map with a key of type String which unique_schemas.containsKey(mapkey.get(0)) would do, since mapKey.get(0) would return the string value for key 0, if it exists.

So try unique_schemas.containsKey(mapkey) instead, to use the entire map as a key, as you specified it.

Btw, I'd most probably refactor that whole construct, since using a map as a key seems quite odd to me. Can the key really contain multiple combinations of id and text? Would it be a problem to have a Map<KeyClass, List<String>> instead, where KeyClass would look like this:

class KeyClass { Integer id; String text; public int hashCode() { ... } public boolean equals(Object o) { ... } } 

Note that this is just a stub and you'd need to expand that, especially the implementation of hashCode() and equals().

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.