Say I'm creating a library which provides amongst other stuff a priority-queue class. The user instantiates one and implements a Comparator interface which is then passed gently to the priority-queue. I want to:
1. grant the user the possibility to define the Comparator class easily - by implementing it as an anonymous class, just like this example suggests:
PriorityQueue<int> pq = new PriorityQueue<int>();
pq.setComparator(new Comparator<int>() {
@Override
public int compare(int i1, int i2){
if(i1 < i2) return -1;
else if(i1 > i2) return 1;
else return 0;
}
};);
2. grant the user the possibility to serialize-and-deserialize the priority queue ALONG with its attached comparator.
3. use only JDK to achieve this, no other external libraries
What approach would be best to achieve this?
Currently I'm having problems deserializing the Comparator class, more specifically creating an instance of it since it's private within the class that created it (that "owns" it) and it also does not have a null-constructor (this is not really a big problem since I can use the available constructors that it exposes).
Thanks for any suggestions in advance.
Document the class, explaining that for the queue to be serialized properly, the comparator should be serializable, and preferrably not an non-static inner class, since this would also cause the serialization of its enclosing object. Also document the fact that the comparator class must be available when deserializing the queue, of course.
java.util.TreeSet
has the same "problem" as the one you have: it takes a comparator as argument, stores it as part of its internal state, and it is serializable. FindBugs generates a warning when you pass a non-serializable comparator to a TreeSet constructor.
I don't think you can do better than that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With