Paragraph 29 in Effective Java provides a way to implement “typical” heterogeneous collections, which basically boil down to something like this:
public Class HeterogeneousContainer {
private Map<Class<?>, Object> container = new HashMap<>();
public <T> put(Class<T> type, T instance) {
container.put(type, instance);
}
public <T> T get(Class<T> type) {
return type.cast(container.get(type));
}
}
Which (I suppose should) be used this way (by the producer):
List<HeterogeneousContainer> resultSet = new ArrayList<>();
...
resultSet.add(new HeterogeneousContainer());
...
resultSet.get(rowIndex).add(Column1.class, column1Value);
resultSet.get(rowIndex).add(Column2.class, column2Value);
...
etc. (by consumer):
for(HeterogeneousContainer row:resultSet) {
Column1 column1Value = row.get(Column1.class);
Column2 column2Value = row.get(Column2.class);
...
}
My question now is why is this type considered safe? How is this better than just putting the column names on the map or just using the regular List/ List<Object>and look at the columns by index?
Does this effectively / practically in any way improve the .getString / .getInt / .getXXXX approach in JDBC result sets?