Qui è un approccio diverso:
classe
un aiutante che contiene una mappa e offre visuali diverse:
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));
}
}
Prima si dovrebbe recuperare un valore int, si dovrebbe controllare il valore di store.containsIntValue(intKey)
e prima di recuperare un valore di stringa, dovresti controllare store.containsStringValue(stringKey)
. In questo modo non recupereresti mai i valori del tipo sbagliato.
(può ovviamente essere esteso per supportare altre tipologie pure)
fonte
2010-09-04 08:03:45
comuni apache multivalore mappa potrebbe risolvere il problema.! –