Re: Delegation and generics craziness
Mark Space wrote:
Tom Anderson wrote:
I may be missing something here, but why is it not just Map<K, V>?
tom
Well, I did that up thread, but I did it quickly and then thought about
it afterwards while I was finishing posting.
What the OP actually has is a constructor that says:
public ExceptionOnDuplicateKeyMap(Map<? extends K, ? extends V>
delegate) {
this.delegate = (Map<K,V>) delegate;
}
And I believe that is a bug waiting to happen! Either the constructor
should accept a Map<K, V>, or you should use:
public ExceptionOnDuplicateKeyMap(Map<? extends K, ? extends V> map) {
this.delegate = new HashMap<K, V>(map);
}
This gains you two things: One, type safety :-), two: It more closely
matches the semantics of other Map implementations (The map-accepting
constructor will copy the map, not create a view/shadow).
So to keep that, I had to cast. But even though the compiler accepted
it, I'm not sure it's correct. For example, if you have a
It isn't correct.
[snip]
Generics are weird enough that figuring out the semantics can be hard
for me even if the syntax is correct. They tend to have tricky corners.
I think the type of "m" should be a upper bound, because that what you
actually have, but that's not what the syntax says.
If you have to cast one generic type to another, then you've probably
done something wrong. If you have to cast a raw-type to a generic type
(or visa-versa) then you'd better be dealing with a legacy API or
writing a reflective framework.
--
Daniel Pitts' Tech Blog: <http://virtualinfinity.net/wordpress/>