Brian

38%
Flag icon
// Typesafe heterogeneous container pattern - implementation public class Favorites {     private Map<Class<?>, Object> favorites = new HashMap<>();     public <T> void putFavorite(Class<T> type, T instance) {         favorites.put(Objects.requireNonNull(type), instance);     }     public <T> T getFavorite(Class<T> type) {         return type.cast(favorites.get(type));     } }
Brian
Do we need to ensure that type is not null here? type.cast() seems problematic in that case? But I’m guessing casting null to any (class) type goes fine, in the case the Set doesn’t have an entry for the given type? Too lazy to test right now. :(
Effective Java
Rate this book
Clear rating
Open Preview