Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: How to make this Serializable?

I need the following class to be Serializable.

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;
    }

}

As of now, I can't send it as an object with outputstream..I´ve tried to implement Serializable, but that didn't work.

like image 242
Lucas Arrefelt Avatar asked Nov 14 '11 00:11

Lucas Arrefelt


People also ask

How do you make something serializable in Java?

To make a Java object serializable you implement the java. io. Serializable interface. This is only a marker interface which tells the Java platform that the object is serializable.

How can an object be serialized in Java?

To serialize an object means to convert its state to a byte stream so that the byte stream can be reverted back into a copy of the object. A Java object is serializable if its class or any of its superclasses implements either the java. io. Serializable interface or its subinterface, java.

How do you mark a class as serializable in Java?

For serializing the object, we call the writeObject() method of ObjectOutputStream class, and for deserialization we call the readObject() method of ObjectInputStream class. We must have to implement the Serializable interface for serializing the object.


2 Answers

Implementing Serializable will do the trick, but you must write the object with an ObjectOutputStream, not just an OutputStream.

like image 157
Mathias Schwarz Avatar answered Oct 07 '22 06:10

Mathias Schwarz


You just need to inherit from java.io.Serializable:

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

Check more about serialization here.

like image 45
Santa Zhang Avatar answered Oct 07 '22 05:10

Santa Zhang