对象持久化

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);
    

    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值