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 [source,java,diff-id=1,diff-type=noncompliant] ---- List collection1 = Collections.EMPTY_LIST; // Noncompliant, raw List Set collection2 = Collections.EMPTY_SET; // Noncompliant, raw Set Map collection3 = Collections.EMPTY_MAP; // Noncompliant, raw Map ---- ==== Compliant solution [source,java,diff-id=1,diff-type=compliant] ---- List collection1 = Collections.emptyList(); // Compliant, List Set collection2 = Collections.emptySet(); // Compliant, Set Map collection3 = Collections.emptyMap(); // Compliant, Map ---- == Resources === Documentation * https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html[Oracle - Java™ Platform, Standard Edition 8 API Specification, Class Collections] * https://docs.oracle.com/javase/tutorial/java/generics/rawTypes.html[Oracle - The Java™ Tutorials - Raw Types] === Articles & blog posts * https://www.baeldung.com/java-generics[Baeldung - The Basics of Java Generics] ifdef::env-github,rspecator-view[] ''' == Implementation Specification (visible only on this page) === Message Replace "Collections.EMPTY_..." by "Collections.empty...()". ''' == Comments And Links (visible only on this page) === on 4 Feb 2014, 08:48:05 Dinesh Bolkensteyn wrote: Implemented by \http://jira.codehaus.org/browse/SONARJAVA-441 endif::env-github,rspecator-view[]