A cast operation makes it possible to convert an object from one type to another one. The compiler raises an error when it can determine that the
target type is incompatible with the declared type of the object. Other cases are accepted by the compiler. However, depending on the actual runtime
type of the object, a cast operation may fail at runtime with a ClassCastException
which can crash the program. This kind of failure
happens when a piece of code makes an invalid assumption about the runtime type of an object.
The appropriate fix for those cast operations highly depends on the context: adding a condition before the cast or changing the runtime type of the
object are some of the possible solutions.
Noncompliant Code Example
List<String> list = new LinkedList<>();
if (someCondition) {
list = new ArrayList<>();
}
((LinkedList<String>) list).addLast("abc"); // Noncompliant, throws a ClassCastException when someCondition is true
Compliant Solution
List<String> list = new LinkedList<>();
if (someCondition) {
list = new ArrayList<>();
}
if (list instanceof LinkedList) {
((LinkedList<String>) list).addLast("abc");
}
or
List<String> list = new LinkedList<>();
if (someCondition) {
list = new ArrayList<>();
}
list.add("abc");
or
LinkedList<String> list = new LinkedList<>();
list.addLast("abc");