Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should a Comparator implement Serializable?

New to Java. Learning it while working on an Android app. I am implementing a Comparator to sort a list of files and the android docs say that a Comparator should implement Serializable:

It is recommended that a Comparator implements Serializable.

This is the Serializable interface here.

I just want to sort a list of files. Why should I implement this or what even is the reason why it should be for any Comparator?

like image 494
Bjorn Avatar asked Dec 27 '11 07:12

Bjorn


1 Answers

This is not just an Android thing, the Java SDK has the same recommendation:

Note: It is generally a good idea for comparators to also implement java.io.Serializable, as they may be used as ordering methods in serializable data structures (like TreeSet, TreeMap). In order for the data structure to serialize successfully, the comparator (if provided) must implement Serializable.

So the idea is that because a TreeMap is serializable, and the TreeMap can contain a Comparator, it would be good if the Comparator is also serializable. The same applies for all elements in the collection.

You can safely ignore this unless you use serialization in that way.

like image 105
Thilo Avatar answered Sep 23 '22 15:09

Thilo