package com.qiku.day21; import java.io.Serializable; import java.util.Objects; public class Student implements Serializable { //1、定义学生类Student ,属性:姓名,学号,年龄,成绩 //提供:无参和全参构造器,生成get和set方法,重写toString ,equals ,hashCode //使用全参构造器创建3个学生对象,放入集合中 //使用对象流将这个学生集合写入到本地 //使用对象流从本地文件把学生信息读出来,并打印 private String name; private int age; private int studentID; protected int score; @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", age=" + age + ", studentID=" + studentID + ", score=" + score + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Student student = (Student) o; return age == student.age && studentID == student.studentID && score == student.score && Objects.equals(name, student.name); } @Override public int hashCode() { return Objects.hash(name, age, studentID, score); } public Student() { } public Student(String name, int age, int studentID, int score) { this.name = name; this.age = age; this.studentID = studentID; this.score = score; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getStudentID() { return studentID; } public void setStudentID(int studentID) { this.studentID = studentID; } public int getScore() { return score; } public void setScore(int score) { this.score = score; } }
package com.qiku.day21; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.util.ArrayList; import java.util.List; public class StudentTest { public static void main(String[] args) throws Exception { Student stu1 = new Student("张三",18,202201,90); Student stu2 = new Student("李四",19,202202,95); Student stu3 = new Student("王五",18,202203,90); List<Student> list = new ArrayList<>(); list.add(stu1); list.add(stu2); list.add(stu3); FileInputStream fis = new FileInputStream("list.Student"); ObjectInputStream ois = new ObjectInputStream(fis); Object o = ois.readObject(); if (o instanceof List){ List list1 = (List) o; for (Object obj: list1){ if (obj instanceof Student){ Student s = (Student) obj; System.out.println(s.getName()); } } } } }
2. package com.qiku.day21; public class MyThread extends Thread { public MyThread() { } public MyThread(String name) { super(name); } @Override public void run() { for (int i = 0; i < 100; i++) { System.out.println(Thread.currentThread().getName()+":" + i); } } }
package com.qiku.day21; public class MyThreadTest { public static void main(String[] args) { MyThread myThread = new MyThread(); MyThread myThread1 = new MyThread("myThread"); myThread.start(); myThread1.start(); } }