Reputation: 3102
I have an object I'm retrieving and turning to a string. The .get() may return null, which in turn crashes when trying to convert to string. What the best way to deal with null in this case? Perhaps set it to an empty string if it returns null. I'm trying to avoid writing an if statement for each .get()
String value1 = userDict.get("key1").toString();
String value2 = userDict.get("key2").toString();
String value3 = userDict.get("key3").toString();
String value4 = userDict.get("key4").toString();
EDIT:
userDict is HashMap (String, Object)
Upvotes: 1
Views: 160
Reputation: 850
I'd use a helper method. Something like this should work..
protected String getStringFromMap(Map<String,Object> map, String key)
{
Object value = map.get(key);
return value != null ? value.toString() : "";
}
Then you can call this as follows:
String value1 = getStringFromMap(userDict, "key1");
String value2 = getStringFromMap(userDict, "key2");
String value3 = getStringFromMap(userDict, "key3");
String value4 = getStringFromMap(userDict, "key4");
Upvotes: 0
Reputation: 155
Try using String.valueOf(userDict.get("key1"))
. According to the specs of valueOf(Object o)
, it will either call toString()
on the object or return the string "null"
if given a null Object.
EDIT: edited to point to the java 7 api instead of the java 6 api.
EDIT 2: If you don't mind making your code a bit more dense, you could encapsulate the logic of this method by using the ternary operator:
String value1 = (userDict.get("key1") == null) ? "" : userDict.get("key1").toString();
Upvotes: 5
Reputation: 54672
As Oli suggested you can create a helper get method like following
String helperGet(String key){
YourClassType t = userDict.get("key1");
if(t!=null)
return t.toString();
else
return "";
}
Now call like following
String value1 = userDict.helperGet("key1");
String value2 = userDict.helperGet("key2");
String value3 = userDict.helperGet("key3");
String value4 = userDict.helperGet("key4");
Upvotes: 0
Reputation: 382
I would use a try-catch
try {
value1 = userDict.get("key1").toString();
} catch (Exception e) {
value1 = 0;
}
Upvotes: -4
Reputation: 272467
Perhaps set it to an empty string if it returns null.
That's up to you. It depends what the purpose of this code is.
I'm trying to avoid writing an if statement for each .get()
If you want to avoid repetitive code, then write yourself a helper method.
Upvotes: 3