繁体   English   中英

每次在对象的序列化之前和序列化之后获得相同的哈希码,而不使用Java中的readResolve方法,为什么?

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

每次在serialization对象之前和对象deserialization serialization之后都获取相同的Hashcode ,而不使用Java中的readResolve()方法,为什么? 这是我的课

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

测试类别

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

}

输出::

instance1 == 1175576​​547

instance2 == 1175576​​547

您的对象是同一类SerializedSingletonClass的实例。 您从类而不是从实例获取hashCode。 instanse1.getClass()计算结果与instance2.getClass()相同,因此,它们当然会产生相同的hashCode。

要查找对象的hashCode,请使用instanse1.hashCode()instance2.hashCode()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM