Non-Serializable Comparator
ID |
java.comparable_should_be_serializable |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Java |
Tags |
CWE:1066, reliability |
Description
Reports a concrete class that implements Comparator without also implementing Serializable.
Rationale
Ordered collections such as TreeMap and TreeSet serialize their comparator along with their elements. If the comparator itself is not Serializable, the whole collection fails to serialize at runtime even though every element it holds is serializable.
// Bad - TreeSet built with this comparator cannot be serialized
public class ByPriority implements Comparator<Task> {
public int compare(Task a, Task b) {
return a.priority() - b.priority();
}
}