[英]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 ? 每次在serialization
对象之前和对象deserialization
serialization
之后都获取相同的Hashcode
,而不使用Java中的readResolve()
方法,为什么? 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 instance1 == 1175576547
instance2==1175576547 instance2 == 1175576547
Your objects are instances of the same class, SerializedSingletonClass. 您的对象是同一类SerializedSingletonClass的实例。 You're getting the hashCode from the class, not from the instance. 您从类而不是从实例获取hashCode。 instanse1.getClass()
evaluates to the same thing as instance2.getClass()
, so of course they produce the same hashCode. instanse1.getClass()
计算结果与instance2.getClass()
相同,因此,它们当然会产生相同的hashCode。
To find the hashCode of the objects, use instanse1.hashCode()
and instance2.hashCode()
. 要查找对象的hashCode,请使用instanse1.hashCode()
和instance2.hashCode()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.