import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
public class Serialization {
public static void main(String[] args) throws Exception {
Person person = new Person("Billy", 18);
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("ser.bin"));
oos.writeObject(person);
}
}
反序列化:
import java.io.FileInputStream;
import java.io.ObjectInputStream;
public class Deserialize {
public static void main(String[] args) throws Exception{
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("ser.bin"));
Object person = ois.readObject();
System.out.println(person);
}
}
// HashMap#readObject
// Read the keys and values, and put the mappings in the HashMap
for (int i = 0; i < mappings; i++) {
K key = (K) s.readObject();
V value = (V) s.readObject();
putVal(hash(key), key, value, false, false);
}
// ====================================================================
// HashMap#hash
// 调用hash是为保证键的唯一性
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
hash方法的参数key的类型是Object,满足参数类型宽泛
最后会调用键对象的hashCode方法。
下面看看URL类的hashCode方法
// URL#hashCode
public synchronized int hashCode() {
if (hashCode != -1)
return hashCode;
hashCode = handler.hashCode(this);
return hashCode;
}
// URLStreamHandler#hashCode
protected int hashCode(URL u) {
InetAddress addr = getHostAddress(u);
// ....
}