Coming from python, I am having trouble with the way java forces one to declare types compared to pythons duck-typing.
In the concrete case, I am trying to pass a map to a function that adds them to a database. The map's keys are strings, the values are of different types for different types of date in the table. like string, date, time, etc
Initially, I had a Map, so values would be all of the same type and I would add them contenValues as below
public long addEntry(Map<String, String> dbEntries, String dbTable) {
ContentValues cv = new ContentValues();
for (String key : dbEntries.keySet()) {
String value = dbEntries.get(key)
cv.put(key, value);
}
return myDataBase.insert(dbTable, null, cv);
}
Now I have values with different types, so I use a Map but then I cant declare a value variable anymore in the loop Note, my question is not related to the ContenValue, but to the problem that I get values from a Map via map.get(key), but can't cast them into a variable because I don't know what type that is without having another map to store that information
public long addEntry(Map<String, Object> dbEntries, String dbTable) {
ContentValues cv = new ContentValues();
for (String key : dbEntries.keySet()) {
// Since I have not only Strings but also other types, this does not work anymore
// How can i declare variables when I don't know their type
String value = dbEntries.get(key)
cv.put(key, value);
}
return myDataBase.insert(dbTable, null, cv);
}
I have no idea how to work around this without having a case check that looks at the keys and then declares the right type based on the key, or some sort of filter function like
public String identifyType(String string) {
return string;
}
public Date identifyType(Date date) {
return date;
}
Also, it seems people sometimes use their own classes to map these things. But I wonder if there is an easier way to do it. It just seems to be a simple problem that should have a simple solution.
Similar questions have been posted, but I dont understand the answers. In particular user2567978's answer here Hashmap holding different data types as values for instance Integer, String and Object
EDIT: Actually, in this case, I may just create contentValues instead of the map and directly pass them through to the function. That should solve my problem as contenValues seems to be already some sort of map. But I'd still appreciate if someone could explain to me how I could make this work when I have a map since the variable declaration in java really confused me now and then