1

I'm getting NotSerializableException and the reason is an anonymous inner class how can I make this customized comparator for a TreeSet implements Serializable interface too .

badPatients = new TreeSet<Patient>(new Comparator <Patient>() {
        public int compare(Patient p1,Patient p2) {
            if(p1.getStatus() > p2.getStatus())
                return -1;
            if(p1.getStatus() == p2.getStatus())
                return 0;
            return 1;
        }
    });
Mahajna
  • 101
  • 6

1 Answers1

1

You can create a custom interface that extends Comparator<T> and also extends Serializable:

SerializableComparator.java

public interface SerializableComparator<T> extends Comparator<T>, Serializable {
    //Nothing here
}

In your code, change the argument from Comparator<Parent> to SerializableComparator<Parent>.

badPatients = new TreeSet<Patient>(new SerializableComparator<Patient>() {
        public int compare(Patient p1,Patient p2) {
            if(p1.getStatus() > p2.getStatus())
                return -1;
            if(p1.getStatus() == p2.getStatus())
                return 0;
            return 1;
        }
    });
Patrick
  • 1,458
  • 13
  • 27