开发者

Java Serialization Comparator

Is it possible to serialize a TreeMap with a comparator??

开发者_运维百科I've tested and it serializes well a treemap without comparator, when you add the comparator, it throws an exception.

If I declare comparator as transient, it still doesn't work. It only works if I make every tree map transient but it doesnt serialize the trees in that case.


All the classes which you attempt to serialize must implement the java.io.Serializable interface. Also, each member variable in your class should be Serializable. In fact, your whole hierarchy should be.


java.util.TreeMap is not a problem, your comparator probably is.

All you need to do is rewrite your comparator class

// throws a 'java.io.NotSerializableException'
class ThisIsNotSerializable implements Comparator<String> {
    public int compare(String o1, String o2) {
        return o1.compareTo(o2);
    }
}

class ThisIsSerializable implements Comparator<String>, Serializable {
    private static final long serialVersionUID = -5972458403679726498L;

    public int compare(String arg0, String arg1) {
        return arg0.compareTo(arg1);
    }
}

more info & source


For more help, look at this. Other things to consider (as mentioned in this document and elsewhere):

  • versioning
  • custom serial forms for objects
  • what fields of your object should be serialized and which ones are transient


TreeMap isn't doing anything special, here. If the only difference between a TreeMap that serializes and one that doesn't is your comparator... then your comparator is not serializable.

How are you implementing the comparator? Your transient declaration is meaningless to the TreeMap class which does not have a transient reference.

What does the exception say?


You might find that it is as simple as changing the Comparator field to a static rather than an instance member:

public final static Comparator<String> ID_IGN_CASE_COMP

You will need to make sure that all the other fields are Serializable but this should be a start.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜