不SerializableException on anonymous class using Comparator

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

NotSerializableException on anonymous class using Comparator

问题

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

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;
    }
});
英文:

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&lt;Patient&gt;(new Comparator &lt;Patient&gt;() {
		public int compare(Patient p1,Patient p2) {
			if(p1.getStatus() &gt; p2.getStatus())
				return -1;
			if(p1.getStatus() == p2.getStatus())
				return 0;
			return 1;
		}
	});

答案1

得分: 1

以下是翻译好的部分:

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

SerializableComparator.java

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

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

badPatients = new TreeSet&lt;Patient&gt;(new SerializableComparator&lt;Patient&gt;() {
        public int compare(Patient p1, Patient p2) {
            if (p1.getStatus() &gt; p2.getStatus())
                return -1;
            if (p1.getStatus() == p2.getStatus())
                return 0;
            return 1;
        }
    });
英文:

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

SerializableComparator.java

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

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

badPatients = new TreeSet&lt;Patient&gt;(new SerializableComparator&lt;Patient&gt;() {
        public int compare(Patient p1,Patient p2) {
            if(p1.getStatus() &gt; p2.getStatus())
                return -1;
            if(p1.getStatus() == p2.getStatus())
                return 0;
            return 1;
        }
    });

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:

确定