48 lines
1.5 KiB
Plaintext
48 lines
1.5 KiB
Plaintext
== Why is this an issue?
|
|
|
|
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
|
|
|
|
[source,java,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
public String [] getStringArray(List<String> strings) {
|
|
return (String []) strings.toArray(); // Noncompliant, a ClassCastException will be thrown here
|
|
}
|
|
----
|
|
|
|
==== Compliant solution
|
|
|
|
[source,java,diff-id=1,diff-type=compliant]
|
|
----
|
|
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
|
|
}
|
|
----
|
|
|
|
== Resources
|
|
|
|
* https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html#toArray-T:A-[docs.oracle] - Collection.toArray()
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
=== Message
|
|
|
|
Pass "new xxx[0]" as an argument to "toArray".
|
|
|
|
|
|
endif::env-github,rspecator-view[]
|