Junior
import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import java.io.*; @XmlAccessorType(XmlAccessType.PROPERTY) @XmlType(name = "Person", propOrder = { "name", "surname", "address", "phone", }) public class Person implements Serializable, Externalizable { private String name; private String surname; public String address; public String phone; public Person(String name, String surname) { this.name = name; this.surname = surname; } public String getName() { return name; } public String getSurname() { return surname; } @Override public int hashCode() { return 1; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Person person = (Person) o; if (name != null ? !name.equals(person.name) : person.name != null) { return false; } if (surname != null ? !surname.equals(person.surname) : person.surname != null) { return false; } return true; } @Override public void writeExternal(ObjectOutput out) throws IOException { out.writeObject(name); out.writeObject(surname); out.writeObject(phone); out.writeObject(address); } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { name = (String) in.readObject(); surname = (String) in.readObject(); address = (String) in.readObject(); phone = (String) in.readObject(); } }
sobes.tech AI
Answer from AI
In this Person class, the interfaces Serializable and Externalizable are implemented, which affects object serialization.
Features:
- Uses @XmlAccessorType(XmlAccessType.PROPERTY), meaning JAXB will work through getters/setters.
- The class implements Externalizable, so the writeExternal and readExternal methods fully control the serialization process.
- writeExternal writes the fields name, surname, phone, address.
- readExternal reads the fields in the same order.
- The name and surname fields are private with getters, while address and phone are public.
- hashCode always returns 1 — this is bad practice and can lead to issues in collections.
- equals compares only name and surname.
Example of serialization with Externalizable:
Person p = new Person("Ivan", "Ivanov");
p.address = "Moscow";
p.phone = "+79991234567";
// Serialization
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("person.dat"))) {
oos.writeObject(p);
}
// Deserialization
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("person.dat"))) {
Person p2 = (Person) ois.readObject();
}
It is important that the order of writing and reading fields in Externalizable strictly matches. Also, the hashCode should be improved for correct operation in hash-based structures.