Re: Delegation and generics craziness
Sideswipe wrote:
I am trying to create a delegate Map that simply throws an exception
if an attempt to insert a duplicate key occurs. That code is simple.
However, the delegate code is not and I am getting compile errors with
regards to my generics.
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;
}
I don't think you have the freedom to use <? extends K> here.
Suppose you have a class hierarchy (Object, A, B), and a Map<B,
something> 'delegate', and an ExceptionOnDuplicateKeyMap<A,something>
'outer' wrapped around it. This should be acceptable to the constructor
and the field, since B extends A.
The constraints on the wrapper class allow you to call outer.put(someA,
someValue), and this maps to:
public V put(K key, V value) {
if(delegate.containsKey(key))
throw new IllegalArgumentException();
return delegate.put(key,value); // error here
}
But 'delegate' only takes B keys - 'A's are too general, and you're
trying to by-pass this restriction. The error is alerting you to this.
Therefore, in this case, you'll have to take a 'delegate' of the form:
Map<K, ? extends V> delegate;
You may have to do something similar with V too; I haven't checked.
(You might be able to use <? super K>, but there are probably other
methods which simultaneously impose <? extends K> or even <K>, so
together they force you to use just <K>.)
--
ss at comp dot lancs dot ac dot uk |