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 Seri
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.