The Collection.toArray()
method returns an Object[]
when no arguments are provided to it. This can lead to a
ClassCastException
at runtime if you try to cast the returned array to an array of a specific type. Instead, use this method by providing
an array of the desired type as the argument.
Note that passing a new T[0]
array of length zero as the argument is more efficient than a pre-sized array new
T[size]
.
Code examples
Noncompliant code example
public String [] getStringArray(List<String> strings) {
return (String []) strings.toArray(); // Noncompliant, a ClassCastException will be thrown here
}
Compliant solution
public String [] getStringArray(List<String> strings) {
return strings.toArray(new String[0]); // Compliant, the toArray method will return an array of the desired type, and we can remove the casting operation
}
public String [] getPresizedStringArray(List<String> strings) {
return strings.toArray(new String[strings.size()]); // Compliant, but slightly less efficient than the previous example
}