Feng Baobao said: array

Chapter IV: array two

1. Array overview and features two

1.1 concept of array two

1.2 creation of array two

1.2.1 dynamically creating arrays two

1.2.2 statically creating arrays two

1.3 basic operation of array three

1.4 default initialization of array five

1.5 heap and stack in JVM (emphasis) five

2. Common operations of array six

2.1 get the latest value of the array six

2.2 index obtained by value six

2.3 array reverse order output seven

2.4 deletion of array elements eight

2.5 array bubble sorting eight

2.6 dichotomy search nine

3.Arrays tools ten

3.1 toString method ten

3.2 equals judgment eleven

3.3 sort sort eleven

3.4 dichotomy search eleven

3.5 fill array eleven

3.6 array copy twelve

4. Supplement of array knowledge points twelve

4.1 for each loop traversal twelve

4.2 formal parameters of main method thirteen

4.3 variable parameters of the method fourteen

5. Two dimensional array fourteen

5.1 definition of two-dimensional array fourteen

5.2 creation of two-dimensional array fourteen

Array overview and features

Concept of array

Array concept: an array is an ordered collection that can store the same data type. (generally speaking, an array is actually a container).

Array creation

Dynamically create an array

Syntax format: element type [] array name = new element type [array length];

Element type: array name [] = new element type [array length];

Note: the first method is recommended for array declaration to avoid confusion of array names.

[example]

public static void main(String[] args) {

    // Create an int type array of 3 spaces

    int[] arr1 = new int[3];

    // Create a String type array of 5 spaces

    String[] arr2 = new String[5];

}

Create array statically

Syntax format: element type [] array name = new element type [] {element 1, element 2, element 3,...};

Note: the array is created statically. The length of the array is determined by the number of elements.

[example]

public static void main(String[] args) {

    // Creates an array of int types for the specified content

    int[] arr1 = new int[]{1, 2, 3, 4, 5};

    // Creates a String type array of the specified content

    String[] arr2 = new String[]{"11", "22", "33", "44"};

}

In addition to using the new keyword to generate an array, you can also directly allocate space and assign values to array elements while defining the array.

Syntax format: element type [] array name = {element 1, element 2, element 3,...};

[example]

public static void main(String[] args) {

    // Creates an array of int types for the specified content

    int[] arr1 = {1, 2, 3, 4, 5};

    // Creates a String type array of the specified content

    String[] arr2 = {"11", "22", "33", "44"};

}

matters needing attention:

  1. Array types can be any data type, including basic types and reference types, such as String [] and float [].
  2. The type of elements stored in the array must be the type specified when creating the array. Mixed types are not allowed.
  3. When creating an array, you must specify the length of the array, and the size of the successfully created array cannot be changed.

Basic operation of array

The elements in the array can be accessed by subscript (index), and the index starts from 0.

The value range of array index is: [0, array length - 1]. If the array element is operated beyond the index range, an ArrayIndexOutOfBoundsException exception will be thrown.

  • Assignment operation of array

[example]

public static void main(String[] args) {

// Initializes an int type array of 5 spaces

    int[] arr = new int[5];

    // Add element

    arr[0] = 11; // Assign a value to the first element

    arr[1] = 22; // Assign a value to the second element

    arr[2] = 22; // Assign a value to the third element

    // Modify the value of the second element

    arr[1] = 222;

}
  • Value taking operation of array

[example]

public static void main(String[] args) {

    // Creates an array of int types for the specified content

    int[] arr = {1, 2, 3, 4, 5};

    // Get element

    int num1 = arr[0]; // Get the first element

    int num2 = arr[1]; // Get the second element

    int num3 = arr[2]; // Get the third element

}
  • Gets the length of the array

[example]

public static void main(String[] args) {

    // Creates an array of int types for the specified content

    int[] arr = {1, 2, 3, 4, 5};

    // Get the length of the array through the length attribute

    System.out.println(arr.length); // Output: 5

}

matters needing attention:

  1. The length of the array obtained through the length attribute is consistent with the length of the opened memory space.
  2. In some cases, the number of elements actually added (not counting the default element) may be less than the length of the array.
  • Traversing an array through a for loop

[example]

public static void main(String[] args) {

    // Creates an array of int types for the specified content

    int[] arr = {1, 2, 3, 4, 5};

    // Get the number of array elements through the length attribute

    int length = arr.length;

    // Through the for loop, traverse all elements of the array

    for(int i = 0; i < length; i++) {

       // Get the elements in the array by subscript

       System.out.println("The first"+(i+1)+"Element values:" + arr[i]);

    }

}

Because the memory space of the array is continuous, we can quickly find the element value corresponding to the array through the first address + index of the array, so as to get the advantage of the array: fast search.

 

Principle of index operation array: array first address + number of bytes storing data * index.

[practice in class]

1. Get the scores of 10 students, then save them in the array, and finally calculate the total score and average score of students.

Default initialization of arrays

Array is a reference type. Once the array is allocated space, each element in the array will be implicitly set to a default value.

The following are the default values for different data types:

1. The default value of basic type variables of integer types (byte, short, int, long) is 0.

2. The default value of basic type variables of floating point type (float, double) is 0.0.

3. The default value of char basic type variable is "/ u0000".

4. The default value of Boolean basic type variables is false.

5. The default value of a variable of reference type is null(null is an empty object).

Heap and stack in (emphasis)

JVM is a stack based virtual machine. Stack is a data structure used to store data. For a Java program, its operation is completed through the operation of the stack.

[stack memory stack]

Stack memory: used to store local variables.

When a variable is defined in a code block, Java allocates memory space for the variable in the stack. When the scope of the variable is exceeded, Java will automatically release the memory space allocated for the variable, which can be used for other purposes immediately.  

Stack memory features:

  1. The stack memory storage feature is "first in first out, last in first out".
  2. Stack is a continuous memory space, which is automatically allocated by the system, with high speed!
  3. The virtual opportunity creates a stack for each thread to store the information of the execution method of the thread.

[heap memory heap]

Heap memory: used to store created objects and arrays (arrays are also objects)

After an array or object is generated in the heap, you can also define a special variable in the stack, so that the value of the variable in the stack is equal to the first address of the array or object in the heap memory, and the variable in the stack becomes the reference variable of the array or object.  
The reference variable is equivalent to a name for the array or object. Later, the reference variable in the stack can be used in the program to access the array or object in the heap.  

When arrays and objects have no reference variables pointing to them, the heap memory occupied by the array or object itself becomes garbage and can no longer be used. Then, the automatic garbage collector of the Java virtual machine manages and releases the memory.  

Heap memory characteristics:

  1. There is only one heap in the virtual machine, which is shared by all threads.
  2. Heap is a discontinuous memory space with flexible allocation but slow speed!

[thinking 1]

public static void main(String[] args) {

    int[] arr1 = {1, 2, 3, 4, 5};

    int[] arr2 = arr1;

    arr2[2] = 33;

    System.out.println(arr1[2]); // The output result is???

}

[thinking 2]

public static void main(String[] args) {

    int[] arr1 = {1, 2, 3};

    int[] arr2 = arr1;

    arr1 = null;

    System.out.println(arr1[2]); // The output result is???

    System.out.println(arr2[2]); // The output result is???

}

2.Array common

operation

Gets the latest value of the array

Requirement: get the maximum value of the array {5, 12, 90, 18, 77, 76, 45, 28, 59, 72}, that is, the element 90 of the array.

Implementation: first assume that the first element is the maximum value and assign it to the maxValue variable for saving, and then take out the elements in the array and maxValue for comparison. If the taken out element is greater than maxValue, set the element to the maximum value.

[example]

reflection

/**

* Gets the maximum value of the array

* @param arr Array to query

* @return Returns the maximum value found in the query

*/

public static int maxElement(int[] arr) {

    // Suppose the value of the first element is the maximum value

    int max = arr[0];

    // Traverse the array elements and compare them with the assumed maximum value in turn

    for(int i = 1; i < arr.length; i++) {

       // Take the value of each element and compare it with value

       if(arr[i] > max) {

           // Overturn the hypothesis and update the maximum value

           max = arr[i];

       }

    }

    return max;

}

: how do we get the index of the maximum value in the array?

Get index by value

Requirement: get the index of element 59 in the array {5, 12, 90, 18, 77, 76, 45, 28, 59, 72}.

Implementation: traverse the array through the for loop, and compare the value to be queried with the elements in the array one by one. If the value to be queried is equal to an element, return the index value and end the method. If it is not found after the loop is completed, it returns - 1.

[example]

/**

* Get its index position in the array according to the value

* @param arr Array to query

* @param value Value to be judged

* @return If found, the corresponding index is returned; If not found, - 1 is returned

*/

public static int search(int[] arr, int value) {

    // Traverse the array and compare the elements in the array with value in turn

    for(int i = 0; i < arr.length; i++) {

       // Take the element value and value for comparison

       if(arr[i] == value) {

           return i; // Find the same element and return the index position

       }

    }

    // If not found, - 1 is returned

    return -1;

}

Array reverse order output

Requirement: output the array in reverse order. The original array {5, 12, 90, 18, 77, 76, 45, 28, 59, 72} is output in reverse order and then {72, 59, 28, 45, 76, 77, 18, 90, 12, 5}.

Implementation (1): introduce an external array variable to save the array in reverse order, and then save the elements in the original array in reverse order in the newly created array.

[example 1]

/**

* Output the array in reverse order

* @param arr An array in reverse order is required

* @return Returns an array in reverse order

*/

public static int[] reverseOrderArray(int[] arr) {

    // Define an array in reverse order

    int[] desArr = new int[arr.length];

    // Traverse the original array elements in reverse order

    for(int i = 0; i < arr.length; i++) {

       // Assign the i-th element of arr to the last i-th element of desArr

       desArr[arr.length - 1 - i] = arr[i];

    }

    // Returns an array in reverse order

    return desArr;

}

Implementation (2): directly carry out the closing exchange of the elements in the array.

[example 2]

/**

* Output the array in reverse order

* @param arr An array in reverse order is required

*/

public static void reverseOrderArray(int[] arr) {

    // Traverse the original array elements in reverse order

    for(int i = 0; i < arr.length/2; i++) {

       // End and swap the elements in the array

       int temp = arr[i];

       arr[i] = arr[arr.length - i - 1];

       arr[arr.length - i - 1] = temp;

    }

}

Array element deletion

Requirement: delete the element with index 2 of array {5, 12, 90, 18, 77, 76, 45, 28, 59, 72}. After deletion: {5, 12, 18, 77, 76, 45, 28, 59, 72, 0}.

Implementation: move the elements after array index 2 forward by one bit, and finally set the value of the last element of the array as the default value (the default value of integer type is 0).

[example]

/**

* Deletes the elements in the array according to the index

* @param arr Array of elements to be deleted

* @param index The index of the array element needs to be deleted

*/

public static void deleteElement(int[] arr, int index) {

    // Step 1: judge whether the index is legal

    if(index < 0 || index >= arr.length) {

       System.out.println("Index out of bounds");

       return; // Illegal index, end method directly

    }

    // Step 2: start with the index element and move the latter element forward one bit

    for(int i = index; i < arr.length - 1; i++) {

// Moves the latter element forward one bit

       arr[i] = arr[i + 1];

    }

    // Step 3: set the last element as the default value

    arr[arr.length - 1] = 0;

}

Disadvantages of array: because the array is a continuous memory space, when the array is deleted and inserted, the efficiency is relatively low!

2.5 array element insertion

Requirement: insert element 222 at the position where the index of array {5, 12, 90, 18, 77, 76, 45, 28, 59, 72} is 2. After insertion: {5, 12, 222, 90, 18, 77, 76, 45, 28, 59, 72}.

Implementation: first prepare to expand the capacity of the array, then move the element after inserting the index position back one bit, and finally insert the element at the position of inserting the index.

[example]

/**

* Inserts an element at the specified position in the array

* @param arr Array of elements to insert

* @param index Where to insert the element

* @param value Element value to insert

* @return Returns an array of successfully inserted elements

*/

public static int[] insertElement(int[] arr, int index, int value) {

    // Step 1: judge whether the index is legal

    if(index < 0 || index >= arr.length) {

       System.out.println("Index out of bounds");

       // Throw an index out of bounds exception (learn from Chapter 6).

       throw new ArrayIndexOutOfBoundsException("Index out of bounds:"+index);

    }

    // Step 2: expand the capacity of the array

    // Create a larger array

    int[] newArr = new int[arr.length + 1];

    // Copy the data in the original array to the newly created array

    for (int i = 0; i < arr.length; i++) {

       newArr[i] = arr[i];// Copy operation

    }

    // Let arr point to the newArr array in the heap

    arr = newArr;

    // Step 3: move the element after inserting the index position one bit back

    for (int i = arr.length - 2; i >= 2; i--) {

       arr[i + 1] = arr[i];

    }

    // Step 4: assign a value to the index position

    arr[index] = value;

    // Returns an array of successfully inserted elements

    return arr;

}

Array bubble sort

Working principle: repeatedly visit the sequence to be sorted, compare two elements at a time, and exchange them if their order is wrong. The work of visiting the sequence is repeated until there is no need to exchange, that is, the sequence has been sorted.

The name of this algorithm comes from the fact that the larger elements will slowly "float" to the top of the sequence through exchange.

[example of ascending order]

/**

* Sort arrays in ascending order (bubble sort)

* @param arr Array to sort

*/

public static void sort(int[] arr) {

    // The external loop controls the number of times. A total of arr.length-1 times are to be executed

    for (int i = 0; i < arr.length - 1; i++) {

       // It is assumed that this cycle has been sorted successfully

       boolean flag = true;

       // The inner loop controls the number of comparisons per trip

       for (int j = 0; j < arr.length - i - 1; j++) {

           // Swap if the previous is greater than the next

           if (arr[j] > arr[j + 1]) {

              int temp = arr[j];

              arr[j] = arr[j + 1];

              arr[j + 1] = temp;

              // If an exchange occurs, it proves that the sorting is not successful

              flag = false; // Overturn the hypothesis

           }

       }

       // Judge whether to continue sorting according to the flag value

       if (flag) break;

}

binary search

Binary search, also known as half search, has the advantages of less comparison times, fast search speed and good average performance; his shortcoming Yes, the table to be queried is required to be an ordered table, and it is difficult to insert and delete. Therefore, the half search method is applicable to the ordered list that does not change frequently but finds frequently.

[example]

public static void main(String[] args) {

    // The array found by dichotomy must be an ordered array

    int[] arr = {0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20};

    // Call the dichotomy lookup to find the index of the lookup element

    int index = binarySearch(arr, 18);

    System.out.println(index); // Output: 9

}

/**

* Use dichotomy to find the index of the element

* @param arr Array to find

* @param value Element value to find

* @return If the return value is a positive number, it proves that it is found; If - 1 is returned, it proves that it is not found.

*/

public static int y(int[] arr, int value) {

    // Minimum index

    int min = 0;

    // Maximum index

    int max = arr.length - 1;

    // Start circular lookup

    while(true) {

       // Get intermediate index

       int mid = (min + max)/2;

       // If arr [mid] > value, it is proved to be in the upper half region

       if(arr[mid] > value) {

           // Update the value of max

           max = mid - 1;

       }

       // If arr [mid] < value, it is proved to be in the lower half

       else if(arr[mid] < value) {

           // Update the value of min

           min = mid + 1;

       }

       // If arr[mid]==value, it proves that it is found

       else {

           return mid;

       }

       // If min > max, it proves that the value is not found

       if(min > max) {

           return -1;

       }

    }

}

Tool class

Arrays is used to operate the array tool class, which defines the static methods of common array operations.

Note: to use the Arrays tool class, you must import the Arrays tool class.

import java.util.Arrays;

Method

public static String toString(Type[] arr) returns the string representation of the specified array content.

[example]

int[] arr = {3, 5, 1, 7, 6, 2, 4};

// Convert array to string output

System.out.println(Arrays.toString(arr)); // Output: [1, 2, 3, 4, 5, 6]

judge

public static boolean equals(Type[] a1, Type[] a2) to judge whether the contents of the two arrays are the same.

[example]

int[] arr1 = {3, 5, 1, 7, 6, 2, 4};

int[] arr2 = {3, 5, 1, 7, 6, 2};

// Determine whether the contents of two arrays are the same

boolean flag = Arrays.equals(arr1, arr2);

System.out.println(flag); // Output: false

sort

public static void sort(Type[] arr) to sort the contents of the array in ascending order.

[example]

int[] arr = {3, 5, 1, 7, 6, 2, 4};

// Sort the contents of the array in ascending order

Arrays.sort(arr);

System.out.println(Arrays.toString(arr)); // Output: [1, 2, 3, 4, 5, 6, 7]

binary search

public static int binarySearch(Type[] arr, Type key) to find the index position of the key in the array. If found, the index position is returned; If not found, a negative number is returned.

Note: the array must be sorted before calling this call.

[example]

// Sorted array

int[] arr = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

// Find 6 the index position in the array

int index = Arrays.binarySearch(arr, 6);

System.out.println(index);  // Output: 6

// Find 18 the index position in the array

index = Arrays.binarySearch(arr, 18);

System.out.println(index);  // Output: - 11, proof not found

Fill array

public static void fill(Type[] a, Type val) to fill the array with the specified content.

[example]

int[] arr = new int[5];

Arrays.fill(arr, 89);

System.out.println(Arrays.toString(arr)); // Output: [89, 89, 89, 89, 89]

Array copy

public static Type[] copyOf(Type[] original, Type newLength), copy from the first element of the array, copy the array of the specified length, and return a new array after copying.

[example]

int[] arr = {1, 2, 3, 4, 5};

int[] newArr = Arrays.copyOf(arr, 3);

System.out.println(Arrays.toString(newArr));  // Output: [1, 2, 3]

public static Type[] copyOfRange(Type[] original, int from, int to), copies the array from the specified range, and returns a new array after copying.

[example]

int[] arr = {1, 2, 3, 4, 5, 6, 7, 8};

int[] newArr = Arrays.copyOfRange(arr, 2, 5);

System.out.println(Arrays.toString(newArr));   // Output: [3, 4, 5]

Array knowledge point supplement

Loop traversal

for each is a powerful loop structure added to java SE 5.0. It can be used to process each element in the array at once (other types of element sets can also be used) without being distracted by specifying the subscript value.

The syntax format of this enhanced for each loop is:

for (type element : array) {

     System.out.println(element); // Output each element in the array

}

[example]

public static void main(String[] args) {

    int[] arr = {1, 2, 3, 4, 5, 6};

    // Traversing arrays through enhanced for loops

    for(int element : arr) {

       // Output the elements of the array in turn

        System.out.println(element);

    }

}

Advantages: simple syntax and higher efficiency than ordinary for loops.

Disadvantages: compared with the ordinary for loop, the enhanced for loop cannot obtain the array subscript.

Formal parameters of method

The function of the parameter string [] args is to pass the parameter into the main method before the main method runs.

  • From the console, enter the parameters passed when compiling and executing the command

For example, the following code:

public static void main(String[] args) {

    System.out.println("args Array length:" + args.length);

    // Traverse each element in args

    for(String arg : args) {

       System.out.println(arg);

    }

}

However, args [] is not assigned at this time. We need to assign it from the console command line, like this:

 

  • Using the string [] args parameter in Eclipse

In the code editing window, right-click

 

The following window appears, switch to (x) = Arguments window, enter parameters, and finally click Run.

 

Variable parameters of method

Variable parameters: applicable to the case where the number of parameters is uncertain but the type is determined. java treats variable parameters as arrays.

We use Represents variable length parameter Between variable type and variable name, whether there is a space before and after.

[example]

public static void main(String[] args) {

    System.out.println(add(1, 2));   // Output: 3

    System.out.println(add(1, 2, 3));  // Output: 6

}

// Variable parameter function

public static int add(int a, int b, int ... arr) {

    int sum = a + b;

    for(int i = 0; i < arr.length; i++) {

       sum += arr[i];

    }

    return sum;

}

Characteristics of variable parameters:

  1. There can be at most one variable parameter in a method, and it can only appear at the end of the parameter list.
  2. When calling a method with variable parameters, you can give any parameter and access the variable parameters in the form of array in the method body.

Two dimensional array

Definition of two-dimensional array

Two dimensional array is essentially an array with array as array elements, that is, "array of arrays". (generally speaking, each element of a two-dimensional array is a one-dimensional array)

Creation of two-dimensional array

  • Format 1: create a two-dimensional array of equal length

Syntax: data type [] [] array name = new data type [m][n];

m: Represents the length of this two-dimensional array.
n: Represents the length of each element in a two-dimensional array.

Note that the following format can also represent a two-dimensional array:

Data type array name [] [] = new data type [m][n];

Data type [] array name [] = new data type [m][n];

  • , create an indefinite length two-dimensional array

Syntax format: data type [] [] array name = new data type [m] [];  

m: Represents the length of this two-dimensional array.
The length of elements in a two-dimensional array is not given and can be dynamically given.

  • , create a static two-dimensional array

Basic format:

Data type [] [] array name = new data type [] [] {{element 1, element 2...}, {element 1, element 2...}, {element 1, element 2...}};

Simplified format:

Data type [] [] array name = {{element 1, element 2...}, {element 1, element 2...}, {element 1, element 2...}};

[practice in class]

  1. There are three classes, three students in the first class, four students in the second class and five students in the third class. It is required to input the scores of students in three classes through the keyboard, and calculate the average scores of students in each class and the total average scores of students in three classes.

Keywords: Algorithm leetcode JavaSE

Added by ktstowell on Thu, 13 Jan 2022 16:28:53 +0200