I'm working on a project, and I'm slightly stuck on one aspect of it. I need to create a class which can manipulate collections of instances of other classes. As part of this, it creates a wrapper object for each instance which has to be able to not only hold the instance, but perform certain operations on it (including equals/hashcode).
So the constructor takes not only the wrapped object, but also a function object which caller tells us can perform these operations in the way desired (which may differ from the native behavior for the contained objects).
Incidentally, I know that what I'm describing here sounds like I'm reinventing part of the Collections framework, but I've simplified here.
public class MapWrapper<K,V> {
private class KeyWrapper<K> {
K key;
public KeyWrapper(K key) {
// ...
}
}
private class ValueWrapper<V> {
V value;
public ValueWrapper(V value) {
// ...
}
}
// ...
HashMap<KeyWrapper<K>, ValueWrapper<V>> map
= new HashMap<KeyWrapper<K>, ValueWrapper<V>> ();
// ...
Everything seems to be okay so far, but I seem to be unable to add entries to my contained map:
public MapWrapper (HashMap<K, V> map) {
// ...
map.put(new KeyWrapper<K>(key), new ValueWrapper<V>(val));
// ...
}
This fails compilation, with this message:
-
"The method put(K, V) in the type HashMap<K,V> is not applicable for the arguments (HashPlus.KeyWrapper, HashPlus.ValueWrapper)
And I'm at a loss. Is this type erasure at work? I wouldn't think so - it's all in the same compilation unit, and it's not dropping to HashMap<Object,Object>
- it's dropping to HashMap<K,V>
, which seems odd.
Thoughts? Pointers to glaring omissions?
Update and solution: Based on recommendations from several responders, I replaced the original "add" line with:
this.map.put(new KeyWrapper<K>(key), new ValueWrapper<V>(val));
And this sorted my problem. Note: one responder suggested that I don't need to parameterize KeyWrapper and ValueWrapper on the put line, but removing that yields "raw type" warnings, so I have left them in.
Thanks to all.