0

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()?

jordan t
  • 136
  • 10
  • It quite obviously isn't the "proper value". Your options are to perform unchecked operations or to pass `K` and `V` as constructor parameters to the class. – chrylis -cautiouslyoptimistic- May 21 '19 at 21:56
  • I couldn't think of a better way to describe the issue other than "proper" but by "proper value", I mean the keys of the map are Strings (in this instance) but when using toArray() it converts it to an Object[] not String[], what do you mean by unchecked operation? – jordan t May 21 '19 at 22:04
  • Possible duplicate of [How to create a generic array in Java?](https://stackoverflow.com/questions/529085/how-to-create-a-generic-array-in-java) – Marvin May 21 '19 at 23:30
  • One solution is to use `List` and `List` instead of arrays. You wouldn't have to do any casts and you wouldn't have this problem. – newacct Jul 08 '19 at 05:20

0 Answers0