Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.ByteArrayInputStream;
- import java.io.ByteArrayOutputStream;
- import java.io.IOException;
- import java.io.ObjectInputStream;
- import java.io.ObjectOutputStream;
- import java.io.Serializable;
- class SerialDemo implements Serializable {
- private final static long serialVersionUID = 1L;
- private String m_name;
- private int m_id;
- public SerialDemo(String name, int id)
- {
- m_name = name;
- m_id = id;
- }
- @Override
- public String toString() {
- return "SerialDemo<" + m_id + ", " + m_name + ">";
- }
- @Override
- public boolean equals(Object other) {
- if (other == null || other.getClass() != this.getClass())
- return false;
- SerialDemo theOther = (SerialDemo) other;
- if (this == theOther)
- return true;
- return m_id == theOther.m_id && m_name.equals(theOther.m_name);
- }
- @Override
- public int hashCode() {
- return (m_id * 0x108421) ^ m_name.hashCode();
- }
- }
- public class MyClass {
- public static void main(String[] args)
- throws IOException, ClassNotFoundException {
- // Starting object value
- SerialDemo original = new SerialDemo("Fred", 1234);
- // Serialize the object to a byte array
- ByteArrayOutputStream outdata = new ByteArrayOutputStream();
- ObjectOutputStream out = new ObjectOutputStream(outdata);
- out.writeObject(original);
- // Capture the "file" data in a byte[] array
- byte[] serialized = outdata.toByteArray();
- // Read back the object from the serialized bytes:
- ByteArrayInputStream indata = new ByteArrayInputStream(serialized);
- ObjectInputStream in = new ObjectInputStream(indata);
- SerialDemo readback = (SerialDemo) in.readObject();
- // Display the results:
- System.out.println("original = " + original);
- System.out.println("readback = " + readback);
- System.out.println("original == readback: " + (original == readback));
- System.out.println("original.equals(readback): " +
- original.equals(readback));
- // The readback object should be a different object, so that
- // (original==readback) is false, but contains the same data,
- // so that original.equals(readback) is true.
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement