I have a generic Container which holds objects of type E:
public class Container<E> {
private final E e;
public Container(E e) {
this.e = e;
}
public E get() {
return e;
}
}
I have a bucket which holds various containers:
public class Bucket {
private final Map<String, Container<?>> containers = new HashMap<>();
public void put(String name, Container<?> container) {
containers.put(name, container);
}
public Container<?> get(String name) {
Container<?> container = containers.get(name);
return container;
}
}
I want to be able to put containers (of various types) into the bucket and retrieve them back in a type-safe way.
Container<Long> longs = new Container<>(100L);
Container<String> strings = new Container<>("Hello");
Bucket bucket = new Bucket();
bucket.put("longs", longs);
bucket.put("strings", strings);
But as you can I lost type-safety:
Container<?> longs1 = bucket.get("longs");
Container<?> strings1 = bucket.get("strings");
I can't seem to figure out what it'd take that would allow me achieve the following:
Container<Long> longs1 = bucket.get("longs");
Container<String> strings1 = bucket.get("strings");