Why should a Comparator implement Serializable?
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.
Serializeable is a blank interface. It does not contain any methods. So, to implement it, all you need to say is implements Serializable
in a class. It's not a huge burden on you. If you extend Comparator
, you don't even need to implement Serializable
because the super class does that for you, and then you don't need to do anything at all to implement Serializable
.
When something implements Serializable
, that means the object can be turned into a byte array at will. This is used for transmission over the Internet, storage in a file, etc. Speaking very roughly, the way serialization works for an object, by default, is to take every object referenced by the object you're trying to serialize, turn each such object into a byte array (i.e. invoke serialization on it recursively), and concatenate the byte arrays to produce a byte array that represents the overall object.
Now, why should a Comparator
implement Serializable
? Let's say you wish to serialize a TreeMap
or some other ordered Collection
. The goal of serialization is to provide a complete representation of an object. Collections like TreeMap
have a Comparator
object in them, so to be able to produce a byte array that captures every aspect of such collections, you need to be able to save the Comparator
as a byte array too. Hence, Comparator
needs to be Serializable
so that other things can be properly serialized.
This should help you out : http://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html
Note: It is generally a good idea for comparators to 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.