Java:如何使这个序列化?

Luc*_*elt 7 java serialization outputstream

我需要以下类是可序列化的。

package helpers;

public class XY implements Comparable<XY>
{
    public int x;
    public int y;

    public XY (int x, int y)
    {
        this.x = x;
        this.y = y;
    }

    public int compareTo( XY other ) 
    {
        String compare1 = this.x + "-" + this.y;
        String compare2 = other.x + "-" + other.y;

        return compare1.compareTo( compare2 );
    }

    public String toString()
    {
        return this.x + "-" + this.y;
    }

}
Run Code Online (Sandbox Code Playgroud)

到目前为止,我无法将它作为带有输出流的对象发送。我尝试实现可序列化,但这没有用。

Mat*_*arz 8

实现Serializable 可以解决问题,但您必须使用ObjectOutputStream编写对象,而不仅仅是 OutputStream。


San*_*ang 5

你只需要继承自java.io.Serializable

public class XY implements Comparable<XY>, java.io.Serializable

在此处查看有关序列化的更多信息。