ArrayList collection Foundation

aggregate

Comparison of differences between sets and arrays

Set basis

Comparison of characteristics between set and array

  • Features of collection class: it provides a storage model with variable storage space, and the stored data capacity can be changed
  • The difference between a set and an array: they all have in common: they are containers for storing data; Difference: the capacity of the array is fixed and the capacity of the collection is variable.
  • If the length of the stored data changes frequently, it is recommended to use a collection.

Array extension: object array

Requirements: encapsulate (Zhang San, 23) (Li Si, 24) (Wang Wu, 25) into three student objects and store them in the array

Then traverse the array and output the student information to the console

Idea:

​ 1. Define student classes ready to encapsulate data

​ 2. Dynamically initialize an array with length of 3 and type of Student

​ 3. Create three student objects as needed

​ 4. Store student objects in an array

​ 5. Traversal array

​ 6. Call the getXXX method of the object to obtain the student information and output it on the console

 public static void main(String[] args) {

        //1. Dynamically initialize an array with length of 3 and type of Student
        Student[] arr = new Student[3];
        //2. Create three student objects according to the needs
        Student student1 = new Student("Zhang San",23);
        Student student2 = new Student("Li Si",24);
        Student student3 = new Student("Wang Wu",25);
        //3. Store the student object in the array
        arr[0]=student1;
        arr[1]=student2;
        arr[2]=student3;
        //4. Traversal array
        for (int i = 0; i < arr.length; i++) {
            Student temp = arr[i];
            System.out.println(temp.getName()+temp.getAge());
            //Objects are stored in the array. The above code is abbreviated
            System.out.println(arr[i].getName()+arr[i].getAge());
        }
    }
		//output
            //Zhang San 23
            //Li Si 24
            //Wang wu25

####Common methods for ArrayList collection

/**
 *
 * ArrayList Common method set
 * add to:
 *      public boolean add(E e)Adds the specified element to the end of this list
 *      public void add(int index, E element)Inserts the specified element into the specified index position in this list
 * Delete:
 *      public boolean remove(Object o)     Delete the specified element and return whether the element is deleted successfully. / / only one element for the collection is deleted
 *      public E remove(int index)           Deletes the element at the specified index and returns the deleted element
 * Modification:
 *      public E set(int index,E element)    Modify the element at the specified index and return the modified element
 * Query:
 *      public E get(int index)             Returns the element at the specified index
 *      public int size()                   Returns the number of elements in the collection
 *
 * */

#####Example

public static void main(String[] args) {
        ArrayList<String> arrayList = new ArrayList<>();
        //Public Boolean add (E) adds the specified element to the end of this list
        arrayList.add("abc");
        arrayList.add("111");
        arrayList.add("222");
        arrayList.add("333");
        arrayList.add("444");
        System.out.println(arrayList);
    //[abc, 111, 222, 333, 444]

        //public void add(int index, E element) inserts the specified element into the specified index position in this list
        arrayList.add(2,"666");
        System.out.println(arrayList);
    //[abc, 111, 666, 222, 333, 444]
	
        // public boolean remove(Object o) deletes the specified element and returns whether the element was deleted successfully
        boolean b1 = arrayList.remove("666");
        boolean b2 = arrayList.remove("888");
        System.out.println(b1);//true
        System.out.println("Delete the nonexistent element and return:"+b2);//false
        //public E remove(int index) deletes the element at the specified index and returns the deleted element (element at index)
        String beRemovedElement = arrayList.remove(0);
        System.out.println(beRemovedElement);
    //abc

        //public E set(int index,E element) modifies the element at the specified index and returns the modified element
        arrayList.set(1,"Modification completed!");
        System.out.println(arrayList);

        // public E get(int index) returns the element at the specified index
        //This method is required to traverse the collection
        System.out.println(arrayList.get(2));
        //public int size() returns the number of elements in the collection
        System.out.println(arrayList);
        System.out.println("There are in the collection"+arrayList.size()+"Elements");
    }

Traversal of ArrayList collection

Requirements: create a collection of stored strings, store three string elements, and use the program to traverse the collection on the console

Idea:

​ 1. Create collection object

​ 2. Adds a string object to the collection

​ 3. Traverse the collection, get each element of the collection, and call the get method to implement it

​ 4. When traversing a collection, the length of the collection should be obtained through the size method

​ 5. General format for traversing collections

public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("abc");
        list.add("Zhang San");
        list.add("Li Si");
        list.add("Xiao Ming");
        list.add("Small day");
        //Shortcut key: collection object list fori
        for (int i = 0; i < list.size(); i++) {
            //i: Each index value
            String s = list.get(i);
            System.out.println(s);
        }
    }
Case of collection traversal
    /*
    *Create a collection of student objects, store three student objects, and use the program to traverse on the console
    * 1.Define student classes
    * 2.Create collection object
    * 3.Create student object
    * 4.Add student object to collection
    * 5.Traversal set, using traversal format
    *
    * */
public static void main(String[] args) {
    //1. Create a collection object
        ArrayList<Student>list = new ArrayList<>();
    //2. Create student object
        Student stu1 = new Student("Zhang San",23);
        Student stu2 = new Student("Li Si",24);
        Student stu3 = new Student("Xiao Ming",25);
    //3. Add student objects to the collection
        list.add(stu1);
        list.add(stu2);
        list.add(stu3);
    //4. Traverse the set, which is implemented in traversal format
        for (int i = 0; i < list.size(); i++) {
            Student s = list.get(i);
            System.out.println(s);
            //At this step, the printout is still the memory address of the student object, and the object element exists in the collection container in the form of memory address
            //You need to call the get method in the student class to print the value
            System.out.println(s.getName()+"....."+s.getAge());
            //The above code can be abbreviated
        	System.out.println(list.get(i).getName()+"...."+list.get(i).getAge());
        }
    }
Keyboard entry case
    /**
    *Create a set to store student objects and store three student objects. Use the program to traverse the set on the console. The student's name and age come from keyboard entry
    Idea:
     * 1.Define student classes
     * 2.Create collection object
     * 3.Enter the data required by the student object with the keyboard
     * 4.Create a student object and assign the data entered by the keyboard to the member variable of the student object
     * 5.Add student object to collection
     * 6.Traversal set, using traversal format
     *
     *Compared with the previous case, the only change is to change the student information written manually into keyboard entry
     * */
public static void main(String[] args) {
	//Create collection object
        ArrayList<Student>list = new ArrayList<>();
            Student stu1 = getStudent();
            Student stu2 = getStudent();
            Student stu3 = getStudent();
            list.add(stu1);
            list.add(stu2);
            list.add(stu3);
        for (int i = 0; i < list.size(); i++) {
            Student student = list.get(i);
            System.out.println(student.getName()+"....."+student.getAge());
        }
    }
	//Enter the data required by the student object with the keyboard
    private static Student getStudent() {
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter student name:");
        String name = sc.next();
        System.out.println("Please enter student age:");
        int age = sc.nextInt();
        Student stu = new Student(name,age);
        return stu;
    }

#####Collection delete element case

//Create a collection for storing strings, store strings internally, delete the specified strings, and print the remaining elements on the console after deletion
/*
*
* 1.Create collection object
* 2.Call the add method to add a string
* 3.Traverse the collection and get each string element
* 4.Add the if judgment, and call the remove method to delete the specified string
* 5.Print collection elements
*
* */

 public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("abc");
        list.add("abd");
        list.add("abf");
        list.add("abg");
        list.add("abc");
        list.add("abc");
        for (int i = 0; i < list.size(); i++) {
            String s = list.get(i);
            if ("abc".equals(s)){
                list.remove(i);
                i--;
                //After an element in the collection is deleted, the following elements will move forward one bit
            }
        }
        System.out.println(list);
    }
Set element filter case

Requirements:

Define a method. The method receives a collection object (the generic type is Student). The method finds out the Student objects younger than 18 and stores them in a new collection object. The method returns a new collection

Idea:

​ 1. Define the method, and the formal parameter of the method is defined as ArrayListlist

​ 2. Method to store the filtered Student object ArrayListnewList

​ 3. Traverse the original collection and get each student object

​ 4. Get the age through the getAge method of the student object and judge whether it is lower than 18

​ 5. Save students under the age of 18 into a new collection

​ 6. Returns a new collection

​ 7. Test the method in the main method

 public static void main(String[] args) {
        ArrayList<Student> list = new ArrayList<>();
        Student stu1 = new Student("Zhang San",21);
        Student stu2 = new Student("Zhang Si",17);
        Student stu3 = new Student("Zhang Wu",19);
        Student stu4 = new Student("Zhang Liu",16);
        Student stu5 = new Student("Zhang Qi",15);
        list.add(stu1);
        list.add(stu2);
        list.add(stu3);
        list.add(stu4);
        list.add(stu5);
//        7. Test the method in the main method
        ArrayList<Student> arrayList = getArrayList(list);
        for (int i = 0; i < arrayList.size(); i++) {
            Student student = arrayList.get(i);
            System.out.println(student.getName()+"...."+student.getAge());
        }
    }
    //    1. Define a method whose formal parameter is ArrayList < student > list
    public static ArrayList<Student> getArrayList(ArrayList<Student> list){
//        2. Define a new set inside the method and prepare to store the filtered Student object ArrayList < student > NEWLIST
        ArrayList<Student>newlist = new ArrayList<>();
//        3. Traverse the original set and get each student object
        for (int i = 0; i < list.size(); i++) {
            Student stu = list.get(i);
//            4. Get the age by calling the getAge method through the student object, and judge whether the age is lower than 18
            int age = stu.getAge();
            if(age<18){
//                5. Save student objects under the age of 18 into a new collection
                newlist.add(stu);
            }
        }
//        6. Return to new collection
        return newlist;
    }

Keywords: Java intellij-idea

Added by pixelsoul on Mon, 27 Dec 2021 03:16:07 +0200