Date: 2012nov11
Language: Java
Q. Java: avoid clutter of 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");