This rule raises an issue when a standalone utility function for sorting is called on a collection object in language versions where the collection type provides its own instance method for sorting.

In Java, this specifically refers to calling Collections.sort() on a List object in Java 8 or later, where List.sort() should be used instead.

Why is this an issue?

In earlier versions of the language, sorting a collection required using a static utility method from a helper class. This approach followed the pattern of having utility functions in separate classes for operations on data structures.

In later versions, the collection interface itself gained its own sorting method. This change embraced a more object-oriented design where the collection can be sorted directly on the instance.

Using the static utility sorting function in modern code is outdated for several reasons:

While the static utility sorting function still works correctly and has the same behavior, using it signals that the code hasn’t been updated to take advantage of newer language features.

In Java specifically, this refers to using Collections.sort() versus the List.sort() method that was introduced in Java 8.

What is the potential impact?

Using a utility class method to sort a collection instead of the collection’s own sorting method has minimal practical impact on the application’s behavior, as both methods produce the same result. However, it affects code maintainability:

How to fix it

Replace Collections.sort(myList) with myList.sort(null). When sorting with the natural order, pass null as the comparator to the sort() method.

Code examples

Noncompliant code example

Collections.sort(myList); // Noncompliant

Compliant solution

myList.sort(null);

Resources

Documentation