Array and Application

catalogue

1> Initial array

1.1 vessel concept

1.2 array concept

1.3 definition of array

1.3.1 static creation

1.3.2 dynamic creation

1.3.3 traversing arrays using loops

1.4 precautions for using arrays

1.5 why learn arrays?

1.6 application of array

1> Initial array

1.1 vessel concept

Used to store data sets, multiple data are stored together, and each data is called the element of the container.

Containers: arrays, collections (dynamic arrays), objects

Containers in life: water cups, classrooms, mobile phones (photos, documents, novels...) computer

Anyway, the knowledge about containers needs to be mastered. (item, account information, chess) database

1.2 array concept

Used to store the same type of data, an ordered collection

explain:

1. Storage is an ordered collection, which is stored in a certain order

2. The data stored in the array is called array elements

3. Array is to operate the elements in the array through subscript (index)

1.3 definition of array

There are two ways to create an array:
    ① Static creation
    ② Dynamic creation

1.3.1 static creation

Data type [] custom array name = {element 1, element 2, element 3, element 4,....};
package com.softeem.array_;
public class ArrayDemo {

    public static void main(String[] args) {

        //Create arrays statically
        //Data type [] custom array name = {element 1, element 2, element 3, element 4,....};

        int[] arr = {12,14,16,18,20};
        //Get the first number in the array by "array name [subscript value]"
        //The index of the array starts from 0. length-1
        System.out.println(arr[0]);
        System.out.println(arr[1]);
        System.out.println(arr[2]);
        System.out.println(arr[3]);
        System.out.println(arr[4]);//20
        //System.out.println(arr[5]);//ArrayIndexOutOfBoundsException: array index out of bounds exception

        //Get the length of the array. Get the length of the array by "array name. Length"
        int length = arr.length;
        System.out.println("length = " + length);//soutv: the value of the output variable

        int i = arr[0];
        System.out.println("i = " + i);//12
        //The array element can be reassigned by "array name [index value] = new value"
        arr[0] = 100;
        System.out.println("arr[0] = " + arr[0]);//100

    }

}

1.3.2 dynamic creation

Data type [] custom array name = new data type [array length];

package com.softeem.array_;
public class ArrayDemo2 {
    public static void main(String[] args) {

        //Dynamically create an array
        //Data type [] custom array name = new data type [array length];
        int[] arr = new int[2];
        //Get first element in array [0]
        System.out.println(arr[0]);//0
        System.out.println(arr[1]);//0

        //assignment
        arr[0] = 4;
        arr[1] = 6;
        //arr[1] = 1.2; //  Error because the array is of type int and cannot store other types of data
        //arr[2] = 8;// Bad assignment because there is no index 2 in the array
        System.out.println(arr[0]);//4
        System.out.println(arr[1]);//6

    }
}

1.3.3 traversing arrays using loops

int[] arr = {12,14,16,18,20};		
		//Loop through the elements in the array
        //Traversal: output the elements in the container from beginning to end
        for(int j =0; j<5 ; j++){
            System.out.print(arr[j]+" ");  //j: 0-4
        }

        System.out.println("\n----------------------------");

        int k = 0;
        while(k<5){
            System.out.print(arr[k]+" ");
            k++;
        }

        System.out.println("\n----------------------------");

        int m = 0;
        do {
            System.out.print(arr[m]+" ");
            m++;
        }while (m<5);

1.4 precautions for using arrays

1. Once the array is defined, the length of the array is fixed
2. The elements in the array should match the type of the array
3. The index range of the array starts from 0 to length-1. If the index exceeds length, an error ArrayIndexOutOfBoundsException will be reported
4. Array is a reference data type. The elements of array can be basic type and reference data type (String)
Element is the default:
Default value for int type array: 0
Default value of double type array: 0.0
Default value of String type array: null means empty
Default value of boolean type array: false
The default value of char type array: \ u0000 means empty

1.5 why learn arrays?

There are the following needs in life: Statistics of the age or achievement of the whole class, personal information, etc. If there is no array, you need to use variables to save. First, you need to create 23 variables, then assign values to save everyone's grades, and then operate. The error rate will be very high and troublesome. We have introduced containers (arrays) to save all data in one container for unified management.

1.6 application of array

1. Access element

Index: every element stored in the array will automatically have a number. We call this number index (subscript). Each element of the array can be accessed through the index of the array.
Method: array name [index]

2. Array length

Array length: each array has a length and is fixed. Java will give an attribute to the array, which can be used to obtain the length of the array
 Method: array name length

3. Array traversal

Array traversal: print each element in the array and print it through a loop
 Traversal method:
        ① for loop, while loop, do while loop
        ② foreach loop (enhanced for loop)
        ③ toString method in Arrays class

foreach loop: simplified for loop shortcut: array name iter

Format: for (element type custom variable name: traversed array name){

Output (custom variable name);

}

package com.softeem.array_;
public class ArrayDemo5 {

    public static void main(String[] args) {

        //Create an array of int types
        //int[] arr2 = {10,20,30,40,50,60,70,80,90};
        int arr[] = {10,20,30,40,50,60,70,80,90};
        //Not recommended
        //int[] arr2 = new int[]{10,20,30,40,50,60};
        //int[] arr3 = new int[3];

        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i]+" ");
        }
        System.out.println("\n-----------------------------");

        //foreach loop: enhanced for loop shortcut: array name iter + enter
        //To simplify the for loop
        /*
            for(Element type (custom variable name: traversal array name){
                Output (variable name);
            }
         */
        for (int i : arr) {
            System.out.print(i+ " ");
        }
    }
}
//The Arrays class is a tool class used to manipulate data, such as array search and sorting
        //toString(int[] arr): returns a string representation of the contents of the specified array
        String[] str_Arr = {"abc","ABC"};
        System.out.println(Arrays.toString(str_Arr));//[abc, ABC]

        System.out.println(str_Arr);//[Ljava.lang.String;@1b6d3586
        //    [      Ljava.lang.String;    @       1b6d3586
        //Memory address value of type connector of one-dimensional array (calculated by HashCode value)
        int[] int_Arr = {10,20,30};
        System.out.println(int_Arr);//[I@4554617c
        System.out.println(Arrays.toString(int_Arr));//[10, 20, 30]

4. Copy of array

Once the length of the array is defined, it cannot be modified, but in the actual demand, the length of the array may be changed due to the uncertainty of the stored data. Therefore, a solution that can modify the length of the array is needed; However, the length of an array cannot be directly modified in Java. The usual approach is to define an array with a larger capacity, and then copy the elements in the original array to the new array one by one.
 

package com.softeem.array_;

import java.util.Arrays;
public class ArraysDemo6 {

    public static void main(String[] args) {

        int[] int_Arr = {10,20,30,40,50,60,70};
        //Array copy: copies elements from one array to another
        //Define a new array
        int[] new_Arr = new int[int_Arr.length];
        for (int i = 0; i < int_Arr.length; i++) {
            //Assign each element in the old array to the new array
            new_Arr[i] = int_Arr[i];
        }
        for (int i : new_Arr) {
            System.out.print(i+" ");
        }
        System.out.println();

        //The System class has a method arraycopy() that implements array copying
        //arraycopy: copies the array in the specified source array from the specified location to the specified location of the target array
        /*
            Parameter description in method:
                 Object src : Source array
                 int srcPos : Start position in source array
                 Object dest : target array
                 int destPos : Start position of target array
                 int length : The number of array elements to copy
         */
        //The method is called through 'System.arraycopy()'
        //int[] int_Arr = {10,20,30,40,50,60,70};
        int[] arr = new int[int_Arr.length];
        System.arraycopy(int_Arr,4,arr,3,3);
        //Print new array
        System.out.println(Arrays.toString(arr));

    }
}

Keywords: Java Back-end

Added by miesemer on Sun, 09 Jan 2022 15:20:25 +0200