Re: Delegation and generics craziness
Roedy Green wrote:
On Mon, 11 Aug 2008 10:00:23 -0700 (PDT), Sideswipe
<christian.bongiorno@gmail.com> wrote, quoted or indirectly quoted
someone who said :
public class ExceptionOnDuplicateKeyMap<K, V> implements Map<K,V> {
private final Map<? extends K, ? extends V> delegate;
public ExceptionOnDuplicateKeyMap(Map<? extends K, ? extends V>
delegate) {
this.delegate = delegate;
}
[snip generics-related errors]
The mismatches are fairly obvious. The problem what do you do to fix
them. Have a look at source code for
[snip docs]
public HashMap(Map<? extends K, ? extends V> m) {
this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1,
DEFAULT_INITIAL_CAPACITY), DEFAULT_LOAD_FACTOR);
putAllForCreate(m);
}
It is similar to what you want to do.
I don't think that's suitable. The HashMap constructor taking another
Map makes a copy of all the entries, and changes to HashMap won't be
reflected in the original Map. Because it's making a copy, it only
needs to do some 'read' operations on the original Map, so it can open
up the constraints on the original Map to <? extends K, ? extends V>.
It won't do anything like m.put(...), which would constrain V, for example.
The OP is attempting to adapt an existing Map with a new Map interface -
changes to the wrapper will be reflected in the base object. All
methods are called, and some impose <? extends K>, and some impose <?
super K>, and similarly for V, so <K,V> is necessary on both the
delegate field and the constructor.
--
ss at comp dot lancs dot ac dot uk |