集合

集合

集合和数组的区别

集合类的特点:提供一种存储空间可变的存储模型,存储的数据容量可以发生改变

数组的特点

数组只能存放同种类型的数据,不能存放其他类型的数据

数组的长度是固定的,不能中途动态添加多余的数据

集合的特点

集合默认是不限制类型的,可以存放多种类型的数据

集合长度是不固定的,可以动态的扩容

ArrayList

概念

可调整大小的数组,实现List接口, 实现所有可选列表操作,并允许所有类型元素,包括null。 除了实现List 接口之外,

该类还提供了一些方法来操纵内部使用的存储列表的数组的大小

如果要限制存储一种类型的数据,需要加泛型ArrayList<>,泛型只能存放引用类型,不能存放基本类型

ArrayList集合常用方法

添加数据

boolean add(E e) //将指定的元素添加到此列表的尾部
    
void add(int index, E element) //将指定的元素插入此列表中的指定位置

模块一

 public static void addStudent(ArrayList<Student> list) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入您的学号");
        String stuNum = sc.next();
        System.out.println("请输入您的姓名");
        String name = sc.next();
        System.out.println("请输入您的年龄");
        int age = sc.nextInt();
        System.out.println("请输入您的出生年月");
        String birthday = sc.next();
        Student stu = new Student(stuNum, name, age, birthday);
        list.add(stu);
        System.out.println("添加成功");
    }

查询获取数据

public E get(int index)   //根据索引获取数据

public int size()  //获取集合元素个数

模块二

public static void checkStudent(ArrayList<Student> list) {
        if (list.size() <= 0) {
            System.out.println("无信息,请输入信息后查询");
        }
        for (int i = 0; i < list.size(); i++) {
            Student stu = list.get(i);
            System.out.println("学号" + "	" + "姓名" + "	" + "年龄" + "	" + "出生日期");
            System.out.println(stu.getNum() + "		" + stu.getName() + "		" + stu.getAge() + "		" + stu.getBirthday());
        }
    }

修改数据

public E set(int index,E element)

模块三

public static void changeStudent(ArrayList<Student> list) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入要修改的学生的学号");
        String changeNum = sc.nextLine();
        int index = getIndex(list, changeNum);
        if (index == -1) {
            System.out.println("查无信息,请重新输入");
        } else {
            System.out.println("请输入您的姓名");
            String name = sc.nextLine();
            System.out.println("请输入您的年龄");
            int age = sc.nextInt();
            System.out.println("请输入您的出生日期");
            String birthday = sc.next();
            Student stu = new Student(changeNum, name, age, birthday);
            list.set(index, stu);
            System.out.println("修改成功");
        }
    }

删除数据

public boolean remove(Object o)

public E remove(int index)

模块四

public static void deleteStudent(ArrayList<Student> list) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入您要修改的学生学号");
        String deleteNum = sc.nextLine();
        int index = getIndex(list, deleteNum);
        if (index == -1) {
            System.out.println("无信息,请输入后再试");
        } else {
            list.remove(index);
            System.out.println("删除成功");
        }
    }
原文地址:https://www.cnblogs.com/tyrion4396/p/13375005.html