Impossible downcast of `toArray` result detectedJAVA-E0386
Attempting to cast the result of Collection.toArray()
to any type other than Object[]
will always fail, resulting in a ClassCastException
.
Bad Practice
This code is casting the result of calling Collection.toArray()
to a subtype of Object[]
, as in:
String[] getAsArray(Collection<String> c) {
return (String[]) c.toArray();
}
This will usually fail by throwing a ClassCastException
. The toArray()
method of almost all collections returns an Object[]
. They can't really do anything else, since the Collection
object does not have any way to determine its generic type.
Recommended
The correct way to obtain an array of the desired type is by providing an empty array argument of the desired type:
c.toArray(new String[0]);
Exceptions
There is one common/known exception to this. The toArray() method of lists returned by Arrays.asList(...)
will return a covariantly typed array. For example, Arrays.asArray(new String[] { "a" }).toArray()
will return a String []
instead of an Object []
.
References
- SpotBugs - BC_IMPOSSIBLE_DOWNCAST_OF_TOARRAY