Sunil Kuntal Sunil Kuntal - 1 year ago 68
Java Question

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

Getting same

every time before
and after
of object without using
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
ObjectOutputStream obs = new ObjectOutputStream(new FileOutputStream(
ObjectInputStream objInputStream = new ObjectInputStream(
new FileInputStream("filename1.ser"));
SerializedSingletonClass instance2 = (SerializedSingletonClass) objInputStream
System.out.println("instance1==" + instanse1.getClass().hashCode());
System.out.println("instance2==" + instance2.getClass().hashCode());


Output ::



Answer Source

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().

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download