[Java course experience] ArrayList collection in Java

Preface

So far, we want to store multiple data, we can use arrays. The length of the array is fixed and cannot adapt to the needs of data changes.
      To solve this problem, Java provides another container java.util.ArrayList collection class, which allows us to store and manipulate data more conveniently.
      ArrayList is also a class provided by JDK, we use it directly


1. Array review

Array format:
         dynamic initialization: data type [] array name = new data type [length]; int [] arr = new int [length];
         static initialization: data type [] array name = new data type [] {element 1, Element 2, element 3}

   Array access:
         get data: arr[index]
         modify data: arr[index] = new value;
         get length: arr.length

举例:
      int[] arr = new int[5];
      int[] arr = new int[] {11, 22, 33};
      String[] arr = new String[4];

The characteristics of the array:
      1. The length of the array is fixed
      2. The array can store basic data types or reference data types


2. Introduction to ArrayList

Check API
   1. Look at the package
         java.util

   2. Look at the description of the class.
         ArrayList is also a container that can store multiple data, and the size can be changed. In the
         future, you will see that you need to add or delete data. It is recommended to use ArrayList
   . 3. Look at the construction method ArrayList() to create an ArrayList. The default capacity is 10

   4. Look at the member method
         boolean add(Xxx x): add a data to the end of the ArrayList

The format of creating an ArrayList (important):
         class name object name = new class name();
         ArrayList list = new ArrayList();
   create an ArrayList object, the stored data type is String

Summary:
    The characteristics of an array: It is a container that can store multiple data
         1. The length is fixed
         2. It can store basic data types and reference data types

   ArrayList collection: is a container that can store multiple data
      1. The length of ArrayList can vary

Code:

public static void main(String[] args) {
    
    
        String[] arr = new String[4];
        arr[0] = "刘德华";
        arr[1] = "张学友";
        arr[2] = "郭富城";
        arr[3] = "黎明";

        // 创建一个ArrayList来存储String类型数据
        ArrayList<String> list = new ArrayList<String>();

        // 添加数据
        // boolean add(Xxx x): 添加一个数据到ArrayList末尾
        list.add("王宝强");
        list.add("陈羽凡");
        list.add("贾乃亮");
        list.add("谢霆锋");

        System.out.println("list = " + list); // [王宝强, 陈羽凡, 贾乃亮, 谢霆锋]
        // ArrayList内部做了特殊处理让我们打印的时候打印的是内容.(toString我们后面会介绍)
    }

Three. ArrayList commonly used methods;

When you have to save multiple data, add or delete. Use ArrayList (commonly used)

Add, check, delete

Increase
      boolean add​(E e) Appends the specified element to the end of this list.
      void add​(int index, E element) Insert the specified element at the specified position in this list.

Check
      E get​(int index) Returns the element at the specified position.

Delete
      E remove​(int index) Delete the element at the specified position in the list.
      boolean remove​(Object o) Removes the first occurrence of the specified element (if it exists) from the list.
Change
      E set​(int index, E element) to replace the element at the specified position in this list with the specified element.

Get the number of elements:
      int size​() Returns the number of elements in this list.

public static void main(String[] args) {
    
    
        // JDK7以后右边<>里面可以省略
        ArrayList<String> list = new ArrayList<>();

        // 增
        // boolean add​(E e) 将指定的元素追加到此列表的末尾。
        list.add("马蓉");
        list.add("白百何");
        list.add("李小璐");
        //                                          0      1        2
        System.out.println("list = " + list); // [马蓉, 白百何, 李小璐]
        // void add​(int index, E element) 在此列表中的指定位置插入指定的元素。
        list.add(1, "张柏芝");
        //                                          0      1         2       3
        System.out.println("list = " + list); // [马蓉, 张柏芝, 白百何, 李小璐]

        // 查: E get​(int index) 返回指定位置的元素。
        String s1 = list.get(1);
        System.out.println("get: " + s1); // get: 张柏芝

        // 删
        // 1.E remove​(int index) 删除该列表中指定位置的元素
        System.out.println("remove1: " + list.remove(0)); // remove1: 马蓉
        System.out.println("list = " + list); // list = [张柏芝, 白百何, 李小璐]

        // 2.boolean remove​(Object o) 根据内容删除第一个出现的数据
        list.add("白百何");
        System.out.println("list = " + list); // list = [张柏芝, 白百何, 李小璐, 白百何]
        list.remove("白百何");             //           0        1       2
        System.out.println("list = " + list); // list = [张柏芝, 李小璐, 白百何]

        // 改 E set​(int index, E element) 修改指定索引位置的数据
        String set = list.set(1, "凤姐");
        System.out.println("set = " + set); // set = 李小璐 返回被修改的数据
        System.out.println("list = " + list); // list = [张柏芝, 凤姐, 白百何]

        // 获取元素的个数: int size​() 返回此列表中的元素数。
        System.out.println(list.size()); // 3
        list.add("如花");
        System.out.println(list.size()); // 4
    }

Four. ArrayList stores strings and traverses

import java.util.ArrayList;
import java.util.Collections;

The case needs to
         create an ArrayList collection that stores strings, store 3 string elements, and use a program to traverse the collection in the console

summary:

ArrayList遍历固定格式
    for (int i = 0; i < list.size(); i++) { // i = 0, 1, 2
        System.out.println(list.get(i));
    }

Code:

public static void main(String[] args) {
    
    
        // 1.创建ArrayList集合
        ArrayList<String> list = new ArrayList<String>();

        // 2.往ArrayList中添加3个字符串数据
        list.add("迪丽热巴"); // 0
        list.add("古力娜扎"); // 1
        list.add("马尔扎哈"); // 2

        // 3.遍历ArrayList集合获取每个数据,进行打印
       /*
        System.out.println(list.get(0)); // 迪丽热巴
        System.out.println(list.get(1)); // 古力娜扎
        System.out.println(list.get(2)); // 马尔扎哈*/
        // 以上代码是重复代码,只有索引在变化.改成循环.次数确定使用for循环遍历
        for (int i = 0; i < list.size(); i++) {
    
     // i = 0, 1, 2
            System.out.println(list.get(i));
        }

        // list.fori: 神操作
        for (int i = 0; i < list.size(); i++) {
    
    
            System.out.println(list.get(i));
        }
    }

Five. ArrayList stores and traverses student objects

Requirements:
      Create a collection to store student objects, store 3 student objects, and use a program to traverse the collection in the console

Analysis:
      1. Define the student class
      2. Create 3 student objects
      3. Create an ArrayList collection to store student data
      4. Add students to the ArrayList collection
      5. Traverse the ArrayList collection. Get each student

Summary:
      1. The object new comes out in the heap. Studetn s1 saves the address of the object
      2.stus.add(s1); Add the object to the collection, the actual addition is the address of the object 3. The
      ArrayList is also the object when it is taken out Address, use Student type variable to save

Code:

1. Self-define student class

2

public static void main(String[] args) {
    
    
        // 2.创建3个学生对象
        Student s1 = new Student("马云", 56); // Student s1 = 7a5d012c;
        Student s2 = new Student("马化腾", 45); // Student s2 = 3fb6a447;
        Student s3 = new Student("刘强东", 46); // Student s3 = 79b4d0f;
        System.out.println("s1 = " + s1); // 7a5d012c;
        System.out.println("s2 = " + s2); // 3fb6a447;
        System.out.println("s3 = " + s3); // 79b4d0f;

        // 3.创建ArrayList集合,用于存储学生数据
        ArrayList<Student> stus = new ArrayList<>();

        // 4.添加学生到ArrayList集合中
        stus.add(s1); // 加进去的是什么? 7a5d012c
        stus.add(s2); // 3fb6a447
        stus.add(s3); // 79b4d0f
        //
        // System.out.println("stus = " + stus);

        // 5.遍历ArrayList集合.得到每个学生
        for (int i = 0; i < stus.size(); i++) {
    
    
            //  System.out.println(stus.get(i)); // 7a5d012c
            Student s = stus.get(i); // i = 0 (7a5d012c)  i = 1 (3fb6a447) i = 2 (79b4d0f)
            System.out.println(s.getName() + "----" + s.getAge());
        }
    }

Six.demo05ArrayList stores student objects and traverses 2

Requirements:
      Create a collection to store student objects, store 3 student objects, and use the program to traverse the collection on the console. The
      student’s name and age come from keyboard entry

Analysis:
      1. Define the student class
      2. Create an ArrayList collection to store student data
      3. Define a method for the user to input data, and create students to add to the collection
      4. Traverse the ArrayList collection. Get each student

Code:

 public static void main(String[] args) {
    
    
        // 2.创建ArrayList集合,用于存储学生数据
        ArrayList<Student> list = new ArrayList<>();

        // 调用方法添加一个学生
        addStudent(list);
        addStudent(list);
        addStudent(list);

        // 4.遍历ArrayList集合.得到每个学生
        for (int i = 0; i < list.size(); i++) {
    
    
            Student stu = list.get(i);
            System.out.println(stu.getName() + "--" + stu.getAge());
        }
    }

    // 3.定义一个方法让用户输入数据,并创建学生添加到集合中
    // 明确返回值类型: 不需要返回值: void
    // 明确参数列表: 创建的学生往哪个集合中添加: 参数列表: ArrayList集合
    public static void addStudent(ArrayList<Student> stus) {
    
    
        // stus = list,就是外部传入的集合
        // 让用户输入学生的姓名和年龄
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入学生的姓名:");
        String name = sc.next();
        System.out.println("请输入学生的年龄:");
        int age = sc.nextInt();

        // 创建学生对象
        Student s = new Student(name, age);

        // 将学生对象添加到集合中
        stus.add(s);
    }

Seven.demo06ArrayList stores basic data types

ArrayList can only store reference data types. It cannot store basic data types.

Java has a corresponding reference data type for each basic data type. The
      corresponding reference data type (packaging class)
      byte Byte
      short Short
      int Integer *****
      long Long
      float Float
      double Double
      char Character *** **
      boolean Boolean

To save the basic data types in our ArrayList, we need to write the corresponding reference data types

Summary:
      ArrayList cannot store basic data types, only reference data types. If you want to store data of basic data types, you need to write a wrapper class

 public static void main(String[] args) {
    
    
        ArrayList<Integer> list = new ArrayList<>();
        list.add(110); // 0
        list.add(119); // 1
        list.add(120); // 2
        list.add(122); // 3

        list.remove(1);

        int sum = 0;
        // 遍历
        for (int i = 0; i < list.size(); i++) {
    
    
            System.out.println(list.get(i));
            sum += list.get(i);
        }

        System.out.println("sum = " + sum);
    }

Guess you like

Origin blog.csdn.net/maikotom/article/details/113804151