不SerializableException on anonymous class using Comparator

huangapple go评论112阅读模式
英文:

NotSerializableException on anonymous class using Comparator

问题

我收到了NotSerializableException,原因是匿名内部类,如何使此自定义比较器为TreeSet也实现Serializable接口。

  1. badPatients = new TreeSet<Patient>(new Comparator<Patient>() {
  2. public int compare(Patient p1, Patient p2) {
  3. if (p1.getStatus() > p2.getStatus())
  4. return -1;
  5. if (p1.getStatus() == p2.getStatus())
  6. return 0;
  7. return 1;
  8. }
  9. });
英文:

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 .

  1. badPatients = new TreeSet&lt;Patient&gt;(new Comparator &lt;Patient&gt;() {
  2. public int compare(Patient p1,Patient p2) {
  3. if(p1.getStatus() &gt; p2.getStatus())
  4. return -1;
  5. if(p1.getStatus() == p2.getStatus())
  6. return 0;
  7. return 1;
  8. }
  9. });

答案1

得分: 1

以下是翻译好的部分:

你可以创建一个自定义接口,它扩展了 Comparator&lt;T&gt; 并且也扩展了 Serializable

SerializableComparator.java

  1. public interface SerializableComparator&lt;T&gt; extends Comparator&lt;T&gt;, Serializable {
  2. // 这里没有内容
  3. }

在你的代码中,将参数从 Comparator&lt;Parent&gt; 更改为 SerializableComparator&lt;Parent&gt;

  1. badPatients = new TreeSet&lt;Patient&gt;(new SerializableComparator&lt;Patient&gt;() {
  2. public int compare(Patient p1, Patient p2) {
  3. if (p1.getStatus() &gt; p2.getStatus())
  4. return -1;
  5. if (p1.getStatus() == p2.getStatus())
  6. return 0;
  7. return 1;
  8. }
  9. });
英文:

You can create a custom interface that extends Comparator&lt;T&gt; and also extends Serializable:

SerializableComparator.java

  1. public interface SerializableComparator&lt;T&gt; extends Comparator&lt;T&gt;, Serializable {
  2. //Nothing here
  3. }

In your code, change the argument from Comparator&lt;Parent&gt; to SerializableComparator&lt;Parent&gt;.

  1. badPatients = new TreeSet&lt;Patient&gt;(new SerializableComparator&lt;Patient&gt;() {
  2. public int compare(Patient p1,Patient p2) {
  3. if(p1.getStatus() &gt; p2.getStatus())
  4. return -1;
  5. if(p1.getStatus() == p2.getStatus())
  6. return 0;
  7. return 1;
  8. }
  9. });

huangapple
  • 本文由 发表于 2020年8月3日 17:51:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/63227222.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定