Skip to content

Instantly share code, notes, and snippets.

@OlgaKulikova
Created October 28, 2014 23:38
Show Gist options
  • Save OlgaKulikova/cc1c61d803360446b752 to your computer and use it in GitHub Desktop.
Save OlgaKulikova/cc1c61d803360446b752 to your computer and use it in GitHub Desktop.
Сериализация. Human
package humanSer;
import java.io.Serializable;
public class Human implements Cloneable, Serializable {
public String name, sex;
public transient int age;
public Human(String name, int age, String sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
@Override
public String toString() {
return name + " " + age + " " + sex;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
Human human = (Human) obj;
return (this.name.equals(human.name)) && (this.age == human.age) && (this.sex.equals(human.sex));
}
}
package humanSer;
// Написать класс «человек». Реализовать его методы clone, equals, hashCode, toString.
import java.io.*;
public class Main {
public static void main(String[] args) {
Human chel1 = null, chel2 = null, chel3 = null;
try {
chel1 = new Human("Sasha", 26, "male");
chel2 = (Human) chel1.clone();
chel3 = new Human("Max", 37, "male");
System.out.println(chel1.toString());
System.out.println(chel2.toString());
System.out.println(chel3.toString());
System.out.println(chel1.equals(chel2));
System.out.println(chel2.equals(chel3));
System.out.println(chel1.hashCode());
System.out.println(chel2.hashCode());
System.out.println(chel3.hashCode());
} catch (CloneNotSupportedException e) {
System.out.println("Error");
}
try {
FileOutputStream fos = new FileOutputStream("temp.out");
ObjectOutputStream oos = new ObjectOutputStream(fos);
try {
oos.writeObject(chel1);
oos.writeObject(chel2);
oos.writeObject(chel3);
} finally {
oos.close();
}
Human newChel;
FileInputStream fis = new FileInputStream("temp.out");
ObjectInputStream ois = new ObjectInputStream(fis);
try {
newChel = (Human) ois.readObject();
System.out.println(newChel.toString());
newChel = (Human) ois.readObject();
System.out.println(newChel.toString());
newChel = (Human) ois.readObject();
System.out.println(newChel.toString());
} finally {
ois.close();
}
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment