Basics of Java (Issue 9): Collections in Java ArrayList && Addition, deletion, modification and query of collections && Implementation of student information management system in Java

⚠️Java Basics Column

⚠ ⚠ Java advanced column! ! ! ! !

⚠ This is the end of the last issue (ninth issue) of Java Basics

Collections in Java

1. What is a set?

  • A collection is a container used to hold data, similar to an array.

The difference from an array is that once the array is defined, the length is fixed.

  • Collections are mutable and are most commonly used in development.

2.ArrayList

2.1 Introduction to ArrayList

ArrayList: It is a variable array. The parameterless structure initializes a space with a length of 10 by default. If it is exceeded, it will be expanded to 1.5 times the original size.

Schematic:
Insert image description here

Use according to the scenario:

  1. If it is fixed, use an array
  2. If it is random and uncertain, use the ArrayList collection to store it.
2.2Usage of ArrayList

Details: When creating objects of StringBuilde, String, and ArrayList, and printing the object names, I don’t see the address values, they are all the contents of the elements!

1. 构造方法: 
		public ArrayList() : 创建一个空的集合容器
		
		
2. 集合容器的创建细节:
		ArrayList list = new ArrayList();
		现象;可以添加任意数据类型
		弊端:数据不严谨

Use format:

        // ArrayList的使用
        ArrayList<String> list = new ArrayList<>();
        list.add("泛型限定后只能添加字符串");
        System.out.println(list);   // [泛型限定后只能添加字符串]
  • <Data type>: Write the data type in it. For jdk7 and above, the following <> can be empty.

  • Generic<>:

    <>: Basic data types cannot appear. If you want to write its basic data type, you must use a wrapper class (there will be a prompt if the first letter is capitalized)

Collection exercises:

        // 1. 创建一个集合容器,内部存储 11.1 22.2 33.3
        ArrayList<Double> num = new ArrayList<>();
        num.add(11.1);
        num.add(22.2);
        num.add(33.3);
        System.out.println(num);

        // 2. 创建一个集合容器,内部存储 张三,李四,王五
        ArrayList<String> string = new ArrayList<>();
        string.add("张三");
        string.add("李四");
        string.add("王五");
        System.out.println(string);
  • Generics are very powerful.
2.3 ArrayList addition
add() method
  • Adds the specified element to the end of the collection.
  • The return value is of boolean type (always true).
add(index, E element) method
  • Insert the element at the specified position (queue-jumping)
  • The return value is empty. If there is an index, there will definitely be an out-of-bounds relationship.
        // add()无参方法
        ArrayList<String> list = new ArrayList<>();
        list.add("liu");
        list.add("jin");
        list.add("tao");
        System.out.println(list);

        // add(index, E element) 带参方法(插入添加)
        list.add(2, "插入");
        list.add(4, "尾部添加");
        System.out.println(list);
  • Remember that adding methods with parameters cannot go out of bounds
2.4 ArrayList deletion
remove(index) method
  • Delete according to the index number, and the return value is the deleted element.
        ArrayList<String> list = new ArrayList<>();
        list.add("张三");
        list.add("李四");
        list.add("王五");
        // remove(index)删除方法
        System.out.println(list); // [张三, 李四, 王五]
        String result = list.remove(1);
        System.out.println(result);   // 李四
        System.out.println(list);   // [张三, 王五]
remove (object) method
  • Delete according to the specified element, the return value is whether it is successful (boolean type)
       // remove(object)删除方法
        System.out.println(list);   // [张三, 王五]
        boolean remove = list.remove("王五");
        System.out.println(remove);     // true
        System.out.println(list);    // [张三]

2.5 ArrayList modification
set(index,element) method
  • Modify the element value of the specified index number and return the overwritten (modified) value.
        ArrayList<String> list = new ArrayList<>();
        list.add("张三");
        list.add("李四");
        list.add("王五");
        // set(index , new element)方法
        String result = list.set(2, "赵六");
        System.out.println(result);  // 王五
        System.out.println(list);   // [张三, 李四, 赵六]
2.6 ArrayList query
get(index) method
  • Get the collection element according to the index number and return the element corresponding to the index
        ArrayList<String> list = new ArrayList<>();
        list.add("张三");
        list.add("李四");
        list.add("王五");
        // 查询(index)方法
        String result = list.get(2);
        System.out.println(result); // 王五
size() method
  • Returns the number of elements in the collection
        // 查询集合长度方法
        int len = list.size();
        System.out.println(len);    // 3

The above are the commonly used operations for collection ArrayList增删改查.

2.7 Small exercises on ArrayList collection
Exercise 1.
需求:创建一个类型为字符串类型的集合,然后取出每一个元素
        ArrayList<String> list = new ArrayList<>();
        list.add("张三");
        list.add("李四");
        list.add("王五");
        for (int i = 0; i < list.size(); i++){
    
    
            System.out.println(list.get(i));
        }
Exercise 2.
需求:定义一个字符串类型的集合,然后对字符串长度为4的元素做打印。
        ArrayList<String> list = new ArrayList<>();
        list.add("12");
        list.add("123");
        list.add("1234");
        list.add("1212");
        list.add("1213");
        list.add("1213213");
        for (int i = 0; i < list.size(); i++) {
    
    
            String s = list.get(i);
            if (s.length() == 4) {
    
    
                System.out.println(s);
            }
        }
Exercise 3.
需求:创建一个存储学生对象的集合,存储三个学生对象,并且打印年龄低于18岁的学生信息

Student class

package com.liujintao.domain;

public class Student {
    
    
    String name;
    int age;

    public Student() {
    
    
    }

    public Student(String name, int age) {
    
    
        this.name = name;
        this.age = age;
    }

    /**
     * 获取
     * @return name
     */
    public String getName() {
    
    
        return name;
    }

    /**
     * 设置
     * @param name
     */
    public void setName(String name) {
    
    
        this.name = name;
    }

    /**
     * 获取
     * @return age
     */
    public int getAge() {
    
    
        return age;
    }

    /**
     * 设置
     * @param age
     */
    public void setAge(int age) {
    
    
        this.age = age;
    }
}

Test class files

package com.liujintao.test;

import com.liujintao.domain.Student;

import java.util.ArrayList;

public class ArrayListText02 {
    
    
    public static void main(String[] args) {
    
    
        Student stu1 = new Student("张三", 24);
        Student stu2 = new Student("李四", 8);
        Student stu3 = new Student("王五", 15);

        // 创建学生集合
        ArrayList<Student> list = new ArrayList<>();
        list.add(stu1);
        list.add(stu2);
        list.add(stu3);

        // 输出年龄小于18岁的学生信息
        for (int i = 0; i < list.size(); i++) {
    
    
            Student age = list.get(i);
            if (age.getAge() == 18) {
    
    
                System.out.println(age.getName() +"---" + age.getAge());
            }
        }
    }

}

Exercise 4.
需求:
    创建一个存储学生对象的集合,存储3个学生对对象,使用程序实现在控制台遍历该集合,学生的姓名和年龄来自于键盘录入。

Test class:

package com.liujintao.test;

import com.liujintao.domain.Student;

import java.util.ArrayList;
import java.util.Scanner;

public class ArrayListText03 {
    
    
    public static void main(String[] args) {
    
    
        ArrayList<Student> list = new ArrayList<>();
        for (int i = 1; i <= 3; i++) {
    
    
            System.out.println("请输入第" + i + "个学生的信息");
            addStudent(list);
        }

        for (int i = 0; i < list.size(); i++) {
    
    
            Student stu = list.get(i);
            System.out.println(stu.getName() + "---" + stu.getAge());
        }
    }


    public static void addStudent(ArrayList<Student> list) {
    
    
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入学生姓名:");
        String name = sc.next();
        System.out.println("请输入学生年龄:");
        int age = sc.nextInt();
        Student stu = new Student(name, age);
        list.add(stu);
    }
}

Student category:

package com.liujintao.domain;

public class Student {
    
    
    String name;
    int age;

    public Student() {
    
    
    }

    public Student(String name, int age) {
    
    
        this.name = name;
        this.age = age;
    }

    /**
     * 获取
     * @return name
     */
    public String getName() {
    
    
        return name;
    }

    /**
     * 设置
     * @param name
     */
    public void setName(String name) {
    
    
        this.name = name;
    }

    /**
     * 获取
     * @return age
     */
    public int getAge() {
    
    
        return age;
    }

    /**
     * 设置
     * @param age
     */
    public void setAge(int age) {
    
    
        this.age = age;
    }
}

Please enter the information of the first student
Please enter the student’s name:
Zhang San
Please enter the student Age:
23
Please enter the second student’s information
Please enter the student’s name:
Li Si
Please enter the age of the student:
24
Please enter the information of the third student< a i=11> Please enter the student’s name: Wang Wu Please enter the student’s age: 25 Zhang San—23 Li Si—24 Wang Wu—25






Exercise 5.
需求:创建一个存储String的集合,内部存储(test, 张三, test,test, 李四)字符串
   删除所有的test字符串,删除后,将集合剩余元素打印在控制台
  • Note that the ArrayList collection shrinks automatically. If it is deleted, it will be filled in, which affects the direction of the reference.

  • Suggestion, remember to clear in the correct order –

  • Just traverse normally in reverse order.

package com.liujintao.test;

import java.util.ArrayList;

public class ArrayListTest04 {
    
    
    public static void main(String[] args) {
    
    
        ArrayList<String> list = new ArrayList<>();
        list.add("test");
        list.add("张三");
        list.add("李四");
        list.add("test");
        list.add("test");
        // 方法一:正序遍历处理
        method1(list);
        // 方法二:倒序遍历处理
        method2(list);
    }

    private static void method2(ArrayList<String> list) {
    
    
        for (int i = list.size() - 1; i >= 0; i--) {
    
    
            String s = list.get(i);
            if ("test".equals(s)) {
    
    
                list.remove(i);
            }
        }
        System.out.println(list);
    }

    private static void method1(ArrayList<String> list) {
    
    
        for (int i = 0; i < list.size(); i++) {
    
    
            String s = list.get(i);
            if ("test".equals(s)) {
    
    
                list.remove(i);
                i--;
            }
        }
        System.out.println(list);
    }
}

Exercise 6.

Requirements: Define a method that accepts a collection object (generic type is Student)

Inside the method, student objects whose age is less than 18 are found

And save the new collection object, the method returns the new collection

package com.liujintao.test;

import com.liujintao.domain.Student;

import java.util.ArrayList;
import java.util.Scanner;

public class ArrayListTest05 {
    
    
    public static void main(String[] args) {
    
    
        ArrayList<Student> list = new ArrayList<>();
        // 初始化JavaBean数据
        list.add(new Student("张三", 13));
        list.add(new Student("李四", 14));
        list.add(new Student("王五", 24));
        list.add(new Student("赵六", 15));
        list.add(new Student("小明", 23));

        ArrayList<Student> result = handleFilter(list);
        // 遍历打印
        for (Student stu : result) {
    
    
            System.out.println(stu.getName() + " --" + stu.getAge());
        }
    }

    /**
     * 过滤学生数据
     * @param list
     * @return ArrayList<Student> list
     */
    private static ArrayList<Student> handleFilter(ArrayList<Student> list) {
    
    
        ArrayList<Student> newList = new ArrayList<>();
        for (Student stu : list) {
    
    
            if (stu.getAge() < 18) {
    
    
                newList.add(stu);
            }
        }
        return newList;
    }


}

Zhang San --13
Li Si --14
Zhaoliu --15

Summary of common methods of Array List

Insert image description here

3. Student Information Management System

Requirements: Complete student information management (implementation of add, delete, modify and check functions)

According to the menu bar (complete the corresponding function);

            System.out.println("1   添加学生");
            System.out.println("2   删除学生");
            System.out.println("3   修改学生");
            System.out.println("4   查看学生");
            System.out.println("5   退出");

Business logic class:

package com.liujintao.priject;

import java.util.ArrayList;
import java.util.Scanner;

public class manageSystem {
    
    
    public static void main(String [] args) {
    
    
        /**
         * 启动
         */
        start();


    }

    /**
     * 系统入口
     */
    public static void start() {
    
    
        // 学生信息库
        ArrayList<Student> list = new ArrayList<>();
        while (true) {
    
    
            System.out.println("-----------------欢迎来到学生管理系统-----------------");
            System.out.println("1   添加学生");
            System.out.println("2   删除学生");
            System.out.println("3   修改学生");
            System.out.println("4   查看学生");
            System.out.println("5   退出");

            System.out.println("请输入您的选择:");
            Scanner sc = new Scanner(System.in);
            sc = new Scanner(System.in);
            int num = sc.nextInt();
            switch (num) {
    
    
                case 1:
                    addStudent(list);
                    break;
                case 2:
                    handleDelete(list);
                    break;
                case 3:
                    changeStudent(list);
                    break;
                case 4:
                    queryStudent(list);
                    break;
                case 5:
                    System.out.println("退出");
                    System.exit(0);
                default:
                    System.out.println("业务暂未开通,请确认后重试!");
                    break;
            }

        }

    }

    /**
     * 添加学生信息
     * @param list
     */
    public static void addStudent(ArrayList<Student> list) {
    
    
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入学生学号");
        String id = sc.next();
        // 下标都不存在,则视为学生信息不存在,放行
        int result = getIndex(id, list);
        if (result == -1) {
    
    
            System.out.println("请输入学生姓名");
            String name = sc.next();
            System.out.println("请输入学生年龄");
            int age = sc.nextInt();
            System.out.println("请输入学生出生日期");
            String datebirth = sc.next();
            Student stu = new Student(id, name, age, datebirth);
            list.add(stu);
            System.out.println("添加成功!");
        } else {
    
    
            System.out.println("该信息已经被使用");
        }

    }

    /**
     * 删除学生信息
     */
    public static void handleDelete (ArrayList<Student> list) {
    
    
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入需要删除的学生学号:");
        String inputId = sc.next();
        // 根据学号拿到学生对象的下标
        int id = getIndex(inputId, list);
        for (int i = 0; i < list.size(); i++) {
    
    
            if (id == -1) {
    
    
                System.out.println("无法删除不存在的学生信息!");
                break;
            } else {
    
    
                list.remove(id);
                System.out.println("删除成功!");
            }
        }
    }

    /**
     * 修改学生信息
     */
    public static void changeStudent(ArrayList<Student> list) {
    
    
        // 拿到需要删除的学生学号,然后再得到下标处理
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入您需要修改的学生编号:");
        String inputId = sc.next();
        // 调用方法处理得到下标
        int index = getIndex(inputId, list);
        if (index != -1) {
    
    
            System.out.println("请输入修改后的姓名:");
            String changeName = sc.next();
            System.out.println("请输入修改后的年龄:");
            int changeAge = sc.nextInt();
            System.out.println("请输入修改后的出生日期:");
            String changeDate = sc.next();
            // 将新的值覆盖
            list.get(index).setId(inputId);
            list.get(index).setName(changeName);
            list.get(index).setAge(changeAge);
            list.get(index).setDatebirth(changeDate);
            System.out.println("修改成功!");
        } else {
    
    
            System.out.println("您需要修改的学生信息不存在!");
        }
    }

    /**
     * 查询学生信息
     */
    public static void queryStudent (ArrayList<Student> list) {
    
    
        System.out.println("学号\t\t\t\t姓名\t年龄\t出生日期");
        for (Student stu : list) {
    
    
            System.out.println(stu.getId() + stu.getName() + stu.getAge() + stu.getDatebirth());
        }
    }

    /**
     * 获取学生在信息库的下标(根据id来判断)
     */
    public static int getIndex(String id, ArrayList<Student> list) {
    
    
        for (int i = 0; i < list.size(); i++) {
    
    
            if (list.get(i).getId().equals(id)) {
    
    
                return i;
            }
        }
        return -1;
    }
}

javaBean data class:

package com.liujintao.priject;
class Student {
    
    
    /**
     * 成员方法学生信息
     * id: 学号
     * name:姓名
     * age:年龄
     * datebirth:出生日期
     */
    private String id;
    private String name;
    private int age;
    private String datebirth;

    /**
     * 初始化数据使用构造器
     */
    public Student() {
    
    
    }

    public Student(String id, String name, int age, String datebirth) {
    
    
        this.id = id;
        this.name = name;
        this.age = age;
        this.datebirth = datebirth;
    }

    /**
     * 获取
     * @return id
     */
    public String getId() {
    
    
        return id;
    }

    /**
     * 设置
     * @param id
     */
    public void setId(String id) {
    
    
        this.id = id;
    }

    /**
     * 获取
     * @return name
     */
    public String getName() {
    
    
        return name;
    }

    /**
     * 设置
     * @param name
     */
    public void setName(String name) {
    
    
        this.name = name;
    }

    /**
     * 获取
     * @return age
     */
    public int getAge() {
    
    
        return age;
    }

    /**
     * 设置
     * @param age
     */
    public void setAge(int age) {
    
    
        this.age = age;
    }

    /**
     * 获取
     * @return datebirth
     */
    public String getDatebirth() {
    
    
        return datebirth;
    }

    /**
     * 设置
     * @param datebirth
     */
    public void setDatebirth(String datebirth) {
    
    
        this.datebirth = datebirth;
    }

}

Insert image description here

Guess you like

Origin blog.csdn.net/Forever_Hopeful/article/details/134620063