Generic types should not be used raw (without type parameters). To fix this issue, add the type parameters.
Why is this an issue?
A generic type is a generic class or interface that is parameterized over types. For example,
java.util.List has one type parameter:
the type of its elements.
When generic types are used raw (without type parameters), the compiler is not able to do generic type checking. For this reason, it is sometimes
necessary to cast objects and defer type-checking to runtime.
What is the potential impact?
When a cast fails, a
ClassCastException is thrown and the program most likely crashes. Therefore, this issue might impact the
availability and reliability of your application.
How to fix it
You should add type parameters. In the case of collections, the type parameter(s) should correspond to the type of elements that the list is
intended to store.
Noncompliant code example
List integers = new ArrayList<>();
// It is possible to add a string to a list that is supposed to be integers only
Integer a = (Integer) integers.get(0); // ClassCastException!
List<Integer> integers = new ArrayList<>();
// The program does not compile anymore with this mistake:
// integers.add("Hello World!");
Integer a = integers.get(0); // No need to cast anymore.
How does this work?
In the noncompliant example,
List is used as a raw type. Even though the list stores integers, the compiler will type its elements as
Object, To use an element of the list as an integer, it needs to be cast first. But elements are not garanteed to be integers. In this
String is erroneously appended to the list, causing the cast to
Integer to fail.
When the type parameter is specified, this bug is detected by the compiler during type-checking. The cast is also unncessary in this case.