I am implementing my own map extending HashMap which forwards operations onto listeners.
When forwarding events to the listeners it parses the keys and values removed, however, I am getting a ClassCastException Object[] cannot be cast to String[]
currently i am overriding the clear() method of HashMap with the following. I know that both the map and the listener have the generic parameters M, K, V, so that isn't an issue.
K[] keys = (K[]) keySet().toArray();
V[] vals = (V[]) this.values().toArray();
super.clear();
Iterator<IMapChangeListener<M, K, V>> it = listeners.iterator();
while (it.hasNext())
{
IMapChangeListener<M, K, V> v = it.next();
//this line throws the ClassCastException
v.mapClear(mapKey, keys, vals);
}
I understand why this is happening, (this.values().toArray()) doesn't have a parameter so it creates an array of Object and not V, whereas if i did this.values().toArray(new V[0]) (if i knew what V was at compile time) but of course I don't.
Is there a solution to this, which doesn't involve parsing the class type to toArray()?