Sunil Kuntal Sunil Kuntal - 3 months ago 12
Java Question

Getting same hashcode every time before serialization and after seriadeserialization of object without using readResolve method in Java why?

Getting same

Hashcode
every time before
serialization
and after
deserialization
of object without using
readResolve()
method in Java why ?
Here is my class

public class SerializedSingletonClass implements Serializable{

private static final long serialVersionUID = 18989987986l;

private SerializedSingletonClass(){};

private static class InstanceHelper {
private static SerializedSingletonClass obj = new SerializedSingletonClass();
}

public static SerializedSingletonClass getInstance(){
return InstanceHelper.obj;
}
}


Test Class --

public class TestSingleton {
public static void main(String[] args) throws FileNotFoundException,
IOException, ClassNotFoundException {
// Test Serialization for singleton pattern
SerializedSingletonClass instanse1 = SerializedSingletonClass
.getInstance();
ObjectOutputStream obs = new ObjectOutputStream(new FileOutputStream(
"filename1.ser"));
obs.writeObject(instanse1);
obs.close();
ObjectInputStream objInputStream = new ObjectInputStream(
new FileInputStream("filename1.ser"));
SerializedSingletonClass instance2 = (SerializedSingletonClass) objInputStream
.readObject();
objInputStream.close();
System.out.println("instance1==" + instanse1.getClass().hashCode());
System.out.println("instance2==" + instance2.getClass().hashCode());
}


}


Output ::

instance1==1175576547

instance2==1175576547

Answer

Your objects are instances of the same class, SerializedSingletonClass. You're getting the hashCode from the class, not from the instance. instanse1.getClass() evaluates to the same thing as instance2.getClass(), so of course they produce the same hashCode.

To find the hashCode of the objects, use instanse1.hashCode() and instance2.hashCode().