Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

send changed hashmap but get the same one using ObjectOutputStream and ObjectInputStream

public static void main(String[] args) throws Exception {
    Socket socket = new Socket("127.0.0.1", 2345);

    ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
    Map<Integer, Integer> testMap = new HashMap<Integer, Integer>();

    testMap.put(1,1);
    oos.writeObject(testMap);
    oos.flush();

    testMap.put(2,2);
    oos.writeObject(testMap);
    oos.flush();

    oos.close();
}


public static void main(String[] args) throws Exception {
    ServerSocket ss = new ServerSocket(2345);
    Socket s = ss.accept();
    ObjectInputStream ois = new ObjectInputStream(s.getInputStream());

    System.out.println((HashMap<Integer, Integer>) ois.readObject());
    System.out.println((HashMap<Integer, Integer>) ois.readObject());

    ois.close;
}

The code above is from two files. When running them, the console prints the same result:

{1=1}
{1=1}

How can this happen?

like image 472
JustFF Avatar asked Aug 06 '26 22:08

JustFF


1 Answers

An ObjectOutputStream remembers the objects it has written already and on repeated writes will only output a pointer (and not the contents again). This preserves object identity and is necessary for cyclic graphs.

So what your stream contains is basically:

  • HashMap A with contents {1:1}
  • pointer: "HashMap A again"

You need to use a fresh HashMap instance in your case.

like image 97
Thilo Avatar answered Aug 08 '26 10:08

Thilo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!