I want to convert an object into a byte array and convert that array back into an object. Everything works fine, besides that the method which converts the array back into an object doesn't print the right object out.
public static List<Person> list_interviewees;
main {
list_interviewees = new ArrayList<Person>();
Person p = new Person();
p.setAge(20);
p.setDegree("bhd");
p.setLastJob("asd");
p.setLastName("Test");
p.setName("Tester");
list_interviewees.add(p);
Person p2 = new Person();
p2.setAge(20);
p2.setDegree("bhd");
p2.setLastJob("asd");
p2.setLastName("QWEQW");
p2.setName("ASAD");
list_interviewees.add(p2);
transferBytes();
}
public static void sendBytes(byte[] b) {
System.out
.println("++++++ This method simulates sending information to other site and reads the data");
System.out.println("Received bytes" + b);
System.out.println("Total bytes" + b.length);
Person p = null;
try (ByteArrayInputStream bis = new ByteArrayInputStream(b);
ObjectInputStream in = new ObjectInputStream(bis);) {
p = (Person) in.readObject();
System.out.println(p.getName() + " " + p.getLastName());
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static void transferBytes() {
try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bos);) {
for (Person p : list_interviewees) {
out.writeObject(p);
sendBytes(bos.toByteArray());
}
} catch (IOException e) {
e.printStackTrace();
}
}
If I run the code above I get the output
++++++ This method simulates sending information to other site and reads the data
Received bytes[B@4aa298b7
Total bytes158
Tester Test
++++++ This method simulates sending information to other site and reads the data
Received bytes[B@4554617c
Total bytes195
Tester Test
Why do I get the name Tester Test twice there? I checked the person which is send through the debugger, it is the correct one, so why does the sendBytes method receive the wrong array?.