Inspectopedia
 
2024.3

Sorted collection with non-comparable elements

Warning
New
Last modified: 03 December 2024

Reports construction of sorted collections, for example TreeSet, that rely on natural ordering, whose element type doesn't implement the Comparable interface.

It's unlikely that such a collection will work properly.

A false positive is possible if the collection element type is a non-comparable super-type, but the collection is intended to only hold comparable sub-types. Even if this is the case, it's better to narrow the collection element type or declare the super-type as Comparable because the mentioned approach is error-prone.

The inspection also reports cases when the collection element is a type parameter which is not declared as extends Comparable. You can suppress the warnings on type parameters using the provided option (for example, to keep the API compatibility).

New in 2018.3