anon
anon

Reputation:

How to remove “Null” key from HashMap<String, String>?

According to Java, HashMap allowed Null as key. My client said

Use HashMap only, Not other like HashTable,ConcurrentHashMap etc. write logic such a way that HashMap don't contains Null as Key in my overall product logic.

I have a options like

  1. Create wrapper class of HashMap and use it everywhere.

    import java.util.HashMap;
    
    public class WHashMap<T, K> extends HashMap<T, K> {
        @Override
        public K put(T key, K value) {
            // TODO Auto-generated method stub
            if (key != null) {
                return super.put(key, value);
            }
            return null;
        }
    
    }
    
  2. I suggested another option like remove null key manually or don't allowed it in each. It is also not allowed as its same operations repeated.

  3. let me know..if I missed any other better approach?

  4. Use HashMap with Nullonly as per java standard.

Let me know what is good approach to handle such case?

Upvotes: 4

Views: 4180

Answers (2)

ruakh
ruakh

Reputation: 183321

Your code is a reasonable way to create a HashMap that can't contain a null key (though it's not perfect: what happens if someone calls putAll and passes in a map with a null key?); but I don't think that's what your client is asking for. Rather, I think your client is just saying that (s)he wants you to create a HashMap that doesn't contain a null key (even though it can). As in, (s)he just wants you to make sure that nothing in your program logic will ever put a null key in the map.

Upvotes: 3

J-J
J-J

Reputation: 5871

Change your put method implementation as follows

        @Override
        public K put(T key, K value) {
            // TODO Auto-generated method stub
            if (key == null) {
              throw new NullPointerException("Key must not be null.");
            }
            return super.put(key, value);
        }

Upvotes: 5

Related Questions