Dave's Brain

Browse - Programming Tips - My code is cluttered by many check for null when using HashMapString,String.

Date: 2012nov11
Language: Java


Q.  My code is cluttered by many check for null when using HashMap<String,String>.
Can I avoid this?

A.  Here's a class that does the same as HashMap<String,String> but
never returns a null.

class GentleMap extends HashMap<String,String> { GentleMap() { super(); } GentleMap(GentleMap in) { super(in); } @Override public String get(Object key) { String val = super.get(key); if (val == null) { val = ""; } return val; } }
Example use. BEFORE
HashMap<String,String> h; ... String val; if ((val = h.get("mykey")) == null) { // Do something }
AFTER
GentleMap h; ... String val = h.get("mykey");

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.