Thursday, May 16, 2013

Sonar: Correctness - Impossible downcast of toArray() result

When we are facing with the Sonar message "Correctness - Impossible downcast of toArray() result" what does this mean?

This message appears when we have something like this:

String[] getAsArray(Collection c) {
  return (String[]) c.toArray();
}


This will usually fail by throwing a ClassCastException.
The correct way to get an array of a specific type from a collection is by the usage of

c.toArray(new String[c.size()]);


that will return a String[], for this scenario.

No comments:

Post a Comment