Here is a different Approach:
A Helper class that contains a map and provides different views of it:
public class ValueStore {
/**
* Inner map to store values.
*/
private final Map<String,Object> inner = new HashMap<String,Object>();
/**
* Returns true if the Value store contains a numeric value for this key.
*/
public boolean containsIntValue(final String key){
return this.inner.get(key) instanceof Integer;
}
/**
* Returns true if the Value store contains a String value for this key.
*/
public boolean containsStringValue(final String key){
return this.inner.get(key) instanceof String;
}
/**
* Returns the numeric value associated with this key.
* @return -1 if no such value exists
*/
public int getAsInt(final String key){
final Object retrieved = this.inner.get(key);
return retrieved instanceof Integer ? ((Integer) retrieved).intValue() : -1;
}
/**
* Returns the String value associated with this key.
* @return null if no such value exists
*/
public String getAsString(final String key){
final Object retrieved = this.inner.get(key);
return retrieved instanceof String ? (String) retrieved : null;
}
/**
* Store a string value.
*/
public void putAsInt(final String key, final int value){
this.inner.put(key, Integer.valueOf(value));
}
/**
* Store an int value.
*/
public void putAsString(final String key, final String value){
this.inner.put(key, value);
}
/**
* Main method for testing.
*/
public static void main(final String[] args) {
final ValueStore store = new ValueStore();
final String intKey = "int1";
final String stringKey = "string1";
final int intValue = 123;
final String stringValue = "str";
store.putAsInt(intKey, intValue);
store.putAsString(stringKey, stringValue);
assertTrue(store.containsIntValue(intKey));
assertTrue(store.containsStringValue(stringKey));
assertFalse(store.containsIntValue(stringKey));
assertFalse(store.containsStringValue(intKey));
assertEquals(123, store.getAsInt(intKey));
assertEquals(stringValue, store.getAsString(stringKey));
assertNull(store.getAsString(intKey));
assertEquals(-1, store.getAsInt(stringKey));
}
}
Before you would retrieve an int value, you would check the value of store.containsIntValue(intKey)
and before you retrieve a String value, you would check store.containsStringValue(stringKey)
. That way you would never retrieve values of the wrong type.
(Can of course be extended to support other types as well)