对象持久化

寵の児 提交于 2019-12-02 11:59:30

package com.ghgj.Buffer;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

/*

  • 1.定义学生类,包含姓名(String name),性别(String gender),

  •     年龄(int age)三个属性,生成空参有参构造,set和get方法,toString方法
    

    2.键盘录入6个学员信息(录入格式:张三,男,25),
    要求有两个相同的信息,将6个学员信息存入到ArrayList集合中
    3.将存有6个学员信息的ArrayList集合对象写入到D:\StudentInfo.txt文件中
    4.读取D:\StudentInfo.txt文件中的ArrayList对象并遍历打印
    5.对ArrayList集合中的6个学生对象进行去重
    */
    public class Test02 {
    public static void main(String[] args) throws Exception {
    List list=new ArrayList<>();
    Student student=new Student(“张三”,“男”,22);
    Student student2=new Student(“张三”,“男”,22);
    Student student3=new Student(“李四”,“男”,32);
    Student student4=new Student(“小花妖”,“女”,12);
    Student student5=new Student(“小花袄”,“女”,23);
    Student student6=new Student(“王五”,“男”,25);
    list.add(student);
    list.add(student2);
    list.add(student3);
    list.add(student4);
    list.add(student5);
    list.add(student6);
    ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream(“student.txt”));
    oos.writeObject(list);
    oos.flush();
    oos.close();

     ObjectInputStream ois=new ObjectInputStream(new FileInputStream("student.txt"));
     List<Student> list2=(List<Student>) ois.readObject();
     List<Student> list3=new ArrayList<>();
     for (Student stu: list2) {
     	System.out.println(stu);
     	
     for (Student stu2: list2) {
     	     boolean isContain=false;
     	for (Student stu3: list3) {
     		if (stu2.getName().equals(stu3.getName())&&stu2.getAge()==stu3.getAge()&&stu2.getGender().equals(stu3.getGender())) {
     			isContain=true;
     		}
     	}if(!isContain) {
     		list3.add(stu2);
     	}
     	/*
     	 * 用两个list去重
     	 * 遍历两个集合,给他们设一个中间变量来记录是否有重复值
     	 * 如果中间变量是false则说明没有重复值就可以把原来的list添加到新的集合里面去
     	 */
     }
     }
     System.out.println("==========取到不重复的值是==============");
     System.out.println(list3);
    

    }

}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!