Skip to content

Instantly share code, notes, and snippets.

@OlgaKulikova
Last active August 29, 2015 14:08
Show Gist options
  • Save OlgaKulikova/84eaf057f21fc007f456 to your computer and use it in GitHub Desktop.
Save OlgaKulikova/84eaf057f21fc007f456 to your computer and use it in GitHub Desktop.
Проект Human. Сериализация, класс Object.
package human10;
import java.io.Serializable;
public class Human implements Serializable {
private String name, sex;
private int age;
public Human(String name, int age, String sex) {
this.name = name;
this.age = age;
this.sex = 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)) && (this.hashCode() == human.hashCode());
}
@Override
public String toString() {
return name + " " + age + " " + sex;
}
@Override
public int hashCode() {
final int num= 31;
int result = 1;
return num * result + age;
}
}
package human10;
// Написать программу, которая запросит ввести с консоли информацию о 10 людях,
// запишет ее на диск, а при следующем старте прочитает записи и выведет сохраненные данные на экран.
// Одинаковые записи должны игнорироваться (Set + equals*).
import java.io.*;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class Main {
public static void main(String[] args) {
File file = new File("D:\\dir\\out.temp");
if (! file.exists()) {
Scanner scan = new Scanner(System.in);
Set<Human> setHuman = new HashSet<>();
for (int i = 3; i > 0; i--) {
System.out.println("Введите имя: ");
String name = scan.nextLine();
System.out.println("Введите возраст: ");
int age = scan.nextInt();
System.out.println("Введите пол: ");
scan.nextLine();
String sex = scan.nextLine();
Human hum = new Human(name, age, sex);
if (! setHuman.contains(hum)) {
setHuman.add(hum);
} else {
System.out.println("Этого человека вы уже ввели!");
i++;
}
}
serialize(setHuman, file);
} else {
deserialize(file);
file.delete();
}
}
public static void serialize(Set<Human> setHuman, File file) {
try {
FileOutputStream fos = new FileOutputStream(file);
try (ObjectOutputStream oos = new ObjectOutputStream(fos)) {
oos.writeObject(setHuman);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void deserialize(File file) {
HashSet<Human> newSetHuman;
try {
FileInputStream fis = new FileInputStream(file);
try (ObjectInputStream ois = new ObjectInputStream(fis)){
newSetHuman = (HashSet<Human>) ois.readObject();
for (Human human : newSetHuman) {
System.out.println(human.toString());
}
}
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment