This rule raises an issue when the Collections.EMPTY_*
fields are used instead of the Collections.empty*()
methods.
Why is this an issue?
Generic types (types with type parameters) have been introduced into Java with language version 1.5. If type parameters are specified for a class
or method, it is still possible to ignore them to keep backward compatibility with older code, which is called the raw type of the class or
interface.
Using raw type expressions is highly discouraged because the compiler cannot perform static type checking on them. This means that the compiler
will not report typing errors about them at compile time, but a ClassCastException
will be thrown during runtime.
In Java 1.5, generics were also added to the Java collections API, and the data structures in java.util
, such as List
,
Set
, or Map
, now feature type parameters. Collections.EMPTY_LIST
, Collections.EMPTY_SET
, and
Collections.EMPTY_MAP
are relics from before generics, and they return raw lists, sets, or maps, with the limitations mentioned
above.
How to fix it
Use:
-
Collections.emptyList()
instead of Collections.EMPTY_LIST
-
Collections.emptySet()
instead of Collections.EMPTY_SET
-
Collections.emptyMap()
instead of Collections.EMPTY_MAP
In addition, there are variants of Collections.empty*()
available also for other collection interfaces, such as
Collections.emptyIterator()
, Collections.emptyNavigableMap()
, Collections.emptySortedSet()
.
Code examples
Noncompliant code example
List<String> collection1 = Collections.EMPTY_LIST; // Noncompliant, raw List
Set<Float> collection2 = Collections.EMPTY_SET; // Noncompliant, raw Set
Map<Int, String> collection3 = Collections.EMPTY_MAP; // Noncompliant, raw Map
Compliant solution
List<String> collection1 = Collections.emptyList(); // Compliant, List<String>
Set<Float> collection2 = Collections.emptySet(); // Compliant, Set<Float>
Map<Int, String> collection3 = Collections.emptyMap(); // Compliant, Map<Int, String>
Resources
Documentation
Articles & blog posts