Why is TypeToken Collections considered Types? (Effective Java # 29)

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) {
        //essentially just 
        //      return (T) container.get(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);
    ...
    //do something with the columnValues
}

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?

+4
1

, , .

  • container , , , .
  • put T T. , container, ( ), .
  • get (return type.cast(container.get(type))), , container put, . , put - , , , -, .

, , , , . , , . , Effective Java, , .

+5

Source: https://habr.com/ru/post/1528862/


All Articles