Why should a Comparator implement Serializable?

前端 未结 5 490
陌清茗
陌清茗 2021-02-02 06:46

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

5条回答
  •  旧巷少年郎
    2021-02-02 07:24

    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.

提交回复
热议问题