hyena said:
hi ,
I am trying to determine the data type of the return value of
HashMap.get(i). Is there some kind of operators or functions to do this?
The keys of the hashmap is always Integer and the value object could be
either Integer or String.
Thanks!
whilst its certainly possible (google 'instanceof') its not usually a
good design choice to mix the value types within a collection.
Preferably, have two collections, one for the Integers one for the Strings.
If this is not possible, write a simple data holder class which you can
store both Integer and String inside it, and add an instance of this
dataholder into the collection.
class DataHolder {
public Integer intValue;
public String stringValue;
}
.....
map.put(key, dataHolder);
Doing this will be a good start along a design path where very quickly
you find that the dataHolder class needs to have some instance methods
too - it becomes a proper class with its own responsibilities.
A contrived example...
renaming DataHolder to 'Address' and the member vars to houseNumber &
streetName, starts to show that those vars mean something.
class Address {
public Integer houseNumber;
public String streetName;
}
Then we might find that Address should be able to save/update its own
values by setting/getting them from a db...
class Address {
public Integer houseNumber;
public String streetName;
public void refresh() {
houseNumber = db.getHouseNumber();
streetName = db.getStreetName;
}
}
HTH
Andrew