array
Definition of array
An array is a data structure used to store a collection of values of the same type. Each value in the array can be accessed through an integer subscript.
- An array is an ordered collection of data of the same type.
- Array describes several data of the same type, which are arranged and combined in a certain order.
- Among them, each data is called an array element, and each array element can access them through the index or subscript (subscript) of the array.
Array declaration creation
-
Format:
Data type stored in array [] array name = data type stored in new array [length]; -
Detailed explanation of array definition format:
- Data type of array storage: what data type can the created array container store.
- []: represents an array.
- Array name: name a variable for the defined array, which meets the identifier specification. You can use the name to operate the array.
- new: keyword, the keyword used to create the array.
- Data type of array storage: what data type can the created array container store.
- [length]: the length of the array, indicating how many elements can be stored in the array container.
- Note: the array has the fixed length feature. Once the length is specified, it cannot be changed.
-
Array variables must be declared before arrays can be used in programs. The following is the syntax for declaring array variables:
dataType[] arrayRefVar; // Preferred method or dataType arrayRefVar[]; // The same effect, but not the preferred method
- The Java language uses the new operator to create arrays. The syntax is as follows:
ataType[] arrayRefVar = new dataType[arraySize];
- The elements of the array are accessed through the index. The array index starts from 0
- Get array length:
arrays.length
Three kinds of initialization
- initiate static
/Static initialization: Creating + assignment int[] a = {1,2,3}; Man[] mans = {new Man(1,1),new Man(2,2)};
- dynamic initialization
//Dynamic initialization: contains default initialization. It is 0 before assignment. int[] a = new int[2]; a[0] = 1; a[1] = 2;
- Default initialization of arrays
- Array is a reference type, and its elements are equivalent to the instance variables of the class. Therefore, once the array is allocated space, each element in it is implicitly initialized in the same way as the instance variables.
Characteristics of array
-
Its length is determined. Once an array is created, its size cannot be changed.
-
Its elements must be of the same type and mixed types are not allowed.
-
The elements in the array can be any data type, including basic types and reference types.
-
Array variables are reference types. Arrays can also be regarded as objects. Each element in the array is equivalent to the member variables of the object.
-
The array itself is an object. In Java, the object is in the heap. Therefore, whether the array saves the original type or other object types, the array object itself is in the heap.
Access to arrays
- Index: each element stored in the array will automatically have a number, starting from 0. This automatic number is called the array index, which can access the elements in the array through the index of the array.
- Format:
Array name [index] - Array length attribute: each array has a length and is fixed. Java gives an attribute to the array to obtain the length of the array. The statement is: array name Length, the execution result of the attribute length is the length of the array, and the result of type int. It can be inferred that the maximum index value of the array is the array name length-1
- Index access to elements in the array:
- Array name [index] = numeric value, assigning values to the elements in the array
- Variable = array name [index], get the elements in the array
Default values for arrays
Array elements have a default value even if we do not assign a value to each element
The default value of byte shot int is 0. The default value of long type is 0L
The default value of float double is the default value of type 0.0 char. It is "\ u0000"
The boolean type is false and the reference type represented by string is null
Array classification (understand)
- Dimension: 1D array 2D array 3D array multidimensional array
- Data type: array of basic type (integer array, floating point array, character array, Boolean array) array of reference type
Storage of arrays in memory
Memory overview
Memory is an important original and temporary storage area in the computer. It is used to run programs. The program we write is stored in the hard disk. The program in the hard disk will not run. It must be put into the memory to run. After running, the memory will be emptied. In order to run programs, Java virtual machine must allocate and manage memory space.
Memory partition of Java virtual machine
In order to improve the operation efficiency, the space is divided into different regions, because each region has a specific data processing mode and memory management mode.
Memory partition of JVM:
[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-afdhzlot-162763271574) (F: \ study \ notes \ screenshot \ Java performance JVM memory model. JPG)]
Heap: store objects or arrays new, and all of them are in memory. If no space is requested, a memory overflow exception will be thrown.
Virtual machine stack: there are "stack frames" in the stack, and each stack frame corresponds to a method call. The stack frame stores the local variable table (variables and object references of basic type data). Operand stacks, method exits, and other information. An exception also occurs when the depth of the stack call is greater than the range allowed by the jvm.
An array memory graph
public static void main(String[] args) { int[] arr = new int[3]; System.out.println(arr);//[I@5f150435 }
When the above method is executed, the output result is[ I@5f150435 , what is this? Is the address of the array in memory. The contents of new are stored in heap memory, while the variable arr in the method stores the address of the array.
Outputting arr[0] will output the elements on the 0 index in the array in the memory address saved by arr
Two array memory graphs
public static void main(String[] args) { int[] arr = new int[3]; int[] arr2 = new int[2]; System.out.println(arr); System.out.println(arr2); }
Two variables point to an array
public static void main(String[] args) { // Define an array to store 3 elements int[] arr = new int[3]; //Array index assignment arr[0] = 5; arr[1] = 6; arr[2] = 7; //Output element values on 3 indexes System.out.println(arr[0]); System.out.println(arr[1]); System.out.println(arr[2]); //Define the array variable arr2 and assign the address of arr to arr2 int[] arr2 = arr; arr2[1] = 9; System.out.println(arr[1]); }
Multidimensional array
-
Multidimensional arrays can be regarded as arrays. For example, a two-dimensional array is a special one-dimensional array, and each element is a one-dimensional array.
-
Two dimensional array
Dynamic initialization: int[][] arr = new int[3][]; arr[0]= new int[3]; arr[1] = new int[5]; arr[2]= new int[4];
Static initialization: int[][] arr = {{2,1,4},{3,1,4,2,1},{3}}; int[][] arr =new int[][]{{2,1,4},{3,1,4,2,1},{3}};
In java, two-dimensional arrays do not have to rely on the regular matrix form.
int[][] arr = new int[3][5]; arr[0][0] = 32; arr[2][4] = 54; //ergodic for(int i = 0 ; i < arr.length;i++){// that 's ok for(int j = 0 ; j < arr[i].length; j++){// column System.out.print(arr[i][j]+" "); } System.out.println();//Wrap at the end of each line } }
Memory structure:
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-jjka2qqu-162763271577) (F: \ study \ notes \ screenshot \ image-20210717142631584.png)]
Interview site: Yang Hui triangle
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
The first line contains 1 element and the nth line contains n elements
The first and last elements of each are 1
Start with the third line for elements other than the first and last
yanghui[i][j] = yanghui[i-1][j-1] + yanghui[i-1][j]
public static void main(String[] args) { int[][] yh = new int[5][]; for(int i = 0 ; i < yh.length; i++){ yh[i] = new int[i+1]; for(int j = 0; j < i + 1;j++){ if(j==0 || i==j){ yh[i][j]= 1; }else{ yh[i][j] = yh[i-1][j-1] + yh[i-1][j]; } } } for(int i = 0 ; i < yh.length;i++){ for(int j = 0 ; j < yh[i].length; j++){ System.out.print(yh[i][j]+" "); } System.out.println(); } }
Common operations for arrays
Array out of bounds exception
- The legal range of the subscript: [0,length-1]. If it exceeds the range, an error will be reported;
public static void main(String[] args){ int[] a=new int[2]; //The length of a is 2, and the subscript is a[0], a[1] System.out.println(a[2]);//a[2] to exceed the set value }
-
Arraylndexofboundsexception: array subscript out of bounds exception!
-
Summary:
- An array is an ordered collection of the same data type (the data type can be any type)
- Arrays are also objects. An array element is equivalent to a member variable of an object
- The length of the array is fixed and immutable. If it exceeds the boundary, it will report: ArrayindexOutofBounds
-
Solution:
Modify the out of bounds array index to the normal range.
Array null pointer exception
public static void main(String[] args) { int[] arr = {1,2,3}; arr = null; System.out.println(arr[0]); }
The line of code arr = null means that the variable arr will not save the memory address of the array, so it is not allowed to operate the array. Therefore, a null pointerexception null pointer exception will be thrown during operation.
Null pointer exception: it means that the variable of reference type does not point to any object (the variable of reference type does not refer to any data)
Solution: give a real heap memory space reference to the variable of reference type.
Performance of null pointer exception in memory graph
Traversal of array
- Array traversal: it is to get each element in the array separately, which is traversal. Traversal is also the cornerstone of array operations.
public static void main(String[] args) { int[] arr = { 1, 2, 3, 4, 5 }; for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); } }
- Enhanced for loop jdk1 5 new): special users read all elements in the array or set (traverse the array or set)
/* *Enhance the type of elements in the array or collection traversed by the first part of for * The second part a is used to store the elements obtained each time * The third part, arr, represents the array or collection object to be convenient */ for (int a : arr){ System.out.println(a); }
- The enhanced for loop is more concise than the ordinary for loop when traversing the whole
- Ordinary for loops can be precisely controlled to each element by index, while enhanced for loops cannot.
Copy of array
public static void main(String[] args) { int[] arrSrc = {2,3,52,11,4,5,43,2,1}; int[] arrDest = new int[arrSrc.length];// The length of the new array must be greater than or equal to the original array for(int i = 0 ; i < arrDest.length;i++){ arrDest[i] = arrSrc[i]; } for(int a : arrDest){ System.out.println(a); } }
public static void main(String[] args) { int[] arrSrc = new int[5]; int[] arrNew=null; int count=0; for(int i = 0 ; i< 100;i++ ){ if(count < arrSrc.length){//When the number of elements in the array is less than the length of the array, data can be saved to the array arrSrc[i]=i;//Adding elements to an array }else{//The number of data in the array is greater than or equal to the length of the array arrNew = new int[arrSrc.length +(int)(arrSrc.length * 0.75)]; for (int j = 0 ; j < arrSrc.length;j++){ arrNew[j]= arrSrc[j]; } arrSrc = arrNew; arrSrc[i]=i;//Adding elements to an array } count++;//Count the number of data in the array } //ergodic for(int a : arrNew){ System.out.println(a); } }
Gets the maximum value in the array
- Get maximum value: find the maximum value from all elements of the array.
- Implementation idea:
- Define variables to hold the elements on the index of array 0
- Traverse the array to get each element in the array
- Compare the traversed element with the variable that holds the value on the index of array 0
- If the value of the array element is greater than the value of the variable, the variable records the new value
- After the array loop is traversed, the variable saves the maximum value in the array
Record the value of the element
public static void main(String[] args) { int[] arr = {2,52,26,22,12,3,223,22,91,81}; // Gets the largest element in the array int max = arr[0];//Suppose the first element is the largest for(int a : arr){ if(a > max){ max = a; } } System.out.println(max); }
Record the location of the element
public static void main(String[] args) { int[] arr = {2,52,26,22,12,3,223,22,91,81}; // Gets the largest element in the array int maxIndex=0; for(int i = 0 ; i < arr.length;i++){ if(arr[i] > arr[maxIndex]){ maxIndex = i; } } System.out.println(arr[maxIndex]); }
Array inversion
- Array inversion: the order of elements in the array is reversed. For example, the original array is 1,2,3,4,5, and the inverted array is 5,4,3,2,1
- Implementation idea: the farthest elements of the array exchange positions.
- To achieve inversion, you need to exchange the positions of the farthest elements of the array
- Define two variables to hold the minimum index and maximum index of the array
- Element exchange position on two indexes
- Minimum index + +, maximum index –, swap positions again
- The minimum index exceeded the maximum index, and the array inversion operation ended
Array as method parameter and return value
In the previous methods, we learned the parameters and return values of methods, but we used basic data types. So can arrays of reference types be passed as method parameters? Of course.
- Array is passed as a method parameter, and the passed parameter is the address of array memory.
Array as method return value
- Array is the return value of the method, and the memory address of the array is returned
- Method parameter type difference
When the parameter of the method is a basic type, the data value is passed. When the reference type is the address of the method, the value passed is
Sparse array
- Requirements: in the preparation of Gobang games, there is the function of saving, exiting or continuing to play.
- Analysis problem: because many values of the two-dimensional array are the default value of 0, a lot of meaningless data are recorded.
- Solution: sparse array
Introduction to sparse array
- When most elements in an array are 0 or the same value array, sparse array can be used to save the array.
- Sparse arrays are handled as follows:
- There are several rows and columns in the record array, and how many different values there are.
- The elements, rows, columns and values with different values are recorded in a small-scale array, so as to reduce the size of the program
public static void main(String[] args) { int[][] array1 = new int[11][11];//0 stands for empty, 1 for sunspot and 2 for white array1[1][2] = 1;//Locate the sunspot array1[2][3] = 2;//Locate Baizi //Output raw data System.out.println("raw data:"); for (int[] ints : array1) { for (int anInt : ints) { System.out.print(anInt+" "); } System.out.println(); } System.out.println("======================"); //Convert to sparse array save //1. Sum the number of valid values int sum = 0; for (int i = 0; i < array1.length; i++) { for (int j = 0; j < array1.length; j++) { if (array1[i][j]!=0){ sum++; } } } System.out.println("Sparse array:"); //2. Create an array of sparse arrays int[][] array2 = new int [sum+1][3];//Determines the data of the first sparse array array2[0][0]= 11; array2[0][1]= 11; array2[0][2]= sum; //3. Store non-zero values in a sparse array int count = 0; for (int i = 0; i <array1.length ; i++) { for (int j = 0; j <array1.length ; j++) { if (array1[i][j] != 0){ count++; array2[count][0] = i; array2[count][1] = j; array2[count][2] = array1[i][j]; } } } System.out.println("order "+" that 's ok "+" column "+" value ");//Print array int xu = 0; for (int[] ints : array2) { System.out.print(xu+" "); for (int anInt : ints) { if (anInt<10){System.out.print(" "+anInt+" ");} else { System.out.print(" "+anInt+" ");} } xu++; System.out.println(); } /* for (int i = 0; i <array2.length ; i++) { System.out.println(array2[i][0]+"\t" +array2[i][1]+"\t" +array2[i][2]+"\t"); }*/ System.out.println("========================"); //Convert to raw data System.out.println("Restore original array:"); int[][] array3 = new int[array2[0][0]][array2[0][1]];//Confirm the overall size of the original array for (int i = 1; i <array2.length ; i++) { array3[array2[i][0]][array2[i][1]]=array2[i][2];//Assign a value to the data of the array } for (int[] ints : array3) { for (int anInt : ints) { System.out.print(anInt+" "); } System.out.println(); } }
Binary search algorithm
Binary search method (half search). The basic idea of binary retrieval method is to assume that the elements in the array are stored (sorted) in order. First, determine the value (key) we want to find. Compare the key with the element in the middle of the array. If key < middle value, it means that the element to be searched is in the left half. If key > middle value, it means that the element to be searched is in the right half. If key = intermediate value, the element in the middle is the element we are looking for.
Binary retrieval method is an efficient retrieval method.
public class SearchKey { public static void main(String[] args) { int[] arr = {12,32, 34,45, 54,65,71,82}; boolean flag = search(arr,32); System.out.println(flag); } /** * * @param arr Is the target array * @param key Is the target value * @return */ public static boolean search(int[] arr, int key){ int start = 0;//Start of lookup int end = arr.length -1;//End of search while(start <= end){ int mid = (start + end ) /2; if(key == arr[mid]){ return true; }else if(key < arr[mid]){ end = mid -1; }else if(key > arr[mid]){ start = mid + 1; } } return false; } }
/** * * @param arr Is the target array * @param key Is the target value * @return Indicates the location of the target element. If - 1 is returned, it indicates that the target element does not exist */ public static int search(int[] arr, int key){ int start = 0;//Start of lookup int end = arr.length -1;//End of search int index= -1; while(start <= end){ int mid = (start + end ) /2; if(key == arr[mid]){ index = mid; return index; }else if(key < arr[mid]){ end = mid -1; }else if(key > arr[mid]){ start = mid + 1; } } return index; } }
Sorting of arrays
Select sort: directly select sort heap sort
Swap sort: Bubble Sort quick sort
Insert sort: direct insert split sort shell sort
Merge sort
Bucket sort
Cardinality sort
Bubble sorting
[[top ten classical sorting algorithms]:( https://www.cnblogs.com/onepixel/p/7674659.html)
The core of bubble sorting is to compare two adjacent numbers in turn. When sorting in ascending order, put the decimal in the front and the large number in the back. Sorting algorithms generally need multiple rounds of comparison. The following is the ascending comparison process of bubble sorting.
- Round 1: first compare the first and second numbers, and put the decimal before and the large number after; Then compare the second number and the third number, put the decimal before and after the large number, and continue until the last two numbers are compared, put the decimal before and after the large number; So far, the first round is over, and the maximum number is put at the end.
- Round 2: still start the comparison from the first logarithm, put the decimal before the large number, and then compare to the penultimate number (the penultimate position is already the largest number). At the end of the second round, get a new maximum number at the penultimate position (in fact, it is the second largest number in the whole series).
To sum up, the function of round I in rounds 1 to n-1 (n is the length of the array, the same below) is to put the largest number I at the n-i subscript of the array. Operate according to this rule until the sorting is finally completed. Because the large number is always put back in the sorting process, which is similar to the bubble rising, it is called bubble sorting.
It can be seen from the above analysis that if the number of sequences to be sorted is n, it needs to go through n-1 rounds to finally complete the sorting. In the first round, the number of comparisons is n-1, and then it is reduced once per round.
public class BubbleSort { public static void main(String[] args) { int[] arr ={3,15,2,6,4,7,9,8}; for(int j = arr.length -1;j > 0 ; j--){//Controls the number of comparisons for(int i = 0 ; i < j;i++){ if(arr[i] > arr[i+1]){//If the front element is larger than the back element, the positions of the two elements are exchanged int temp = arr[i]; arr[i]= arr[i +1]; arr[i + 1] = temp; } } } for(int a : arr){ System.out.println(a); } } }
Code refactoring:
1. Make the structure of the code clearer and easy to read and maintain
2. Enable code reuse and reduce code redundancy
public class BubbleSort { public static void main(String[] args) { int[] arr ={3,15,2,6,4,7,9,8}; sort(arr); print(arr); } // Use the bubble algorithm to sort integer arrays public static void sort(int[] arr){ for(int j = arr.length -1;j > 0 ; j--){//Controls the number of comparisons for(int i = 0 ; i < j;i++){ if(arr[i] > arr[i+1]){//If the front element is larger than the back element, the positions of the two elements are exchanged swap(arr,i,i+1); } } } } // Swap the positions of two in the array public static void swap(int[] arr, int index1, int index2){ int temp = arr[index1]; arr[index1]= arr[index2]; arr[index2] = temp; } //Traversal of array public static void print(int[] arr){ for(int a : arr){ System.out.println(a); } } }
Quick sort
Quick sort adopts a divide and conquer idea, which can be regarded as an upgraded version of bubble sort
Thought:
1 select an element from the array, which is called "base element"“
2 reorder the array. All elements smaller than the benchmark element are placed in front of the benchmark element, and all elements larger than the benchmark element are placed behind the benchmark element. At the end of this partition, the base element is in the middle of the array. This is called a partition operation.
3 recursively sort the subarray less than the reference element and the subarray greater than the reference element
The bottom case of recursion is that the size of the sequence is zero or 1, that is, it has always been sorted. Although this recursion continues, the algorithm will always end, because at least one element will be placed in its last position in each iteration.
public class QuciSort { public static void main(String[] args) { int[] arr ={3,15,2,6,4,7,9,8}; quickSort(arr); print(arr); } public static void quickSort(int[] arr){ if(arr == null || arr.length == 0 ){ return; } sort(arr,0,arr.length - 1); } // Core algorithm public static void sort(int[] arr,int left,int right){ if(left > right){//End condition of recursion return; } // Select base element int base = arr[left]; int i = left; int j = right; while( i != j){ while(arr[j] >= base && i < j){//Look for elements larger than the base element from the right. If larger than the base element, continue to look forward j--; } // Look from left to right for those smaller than the benchmark element. If they are smaller than the benchmark element, continue to look back while(arr[i] <= base && i < j){ i++; } if(i < j ){// If you find one smaller than the reference element from right to left and one larger than the reference element from left to right, exchange the positions of the two elements so that the large area is on the right and the small one is on the left int temp = arr[i]; arr[i] =arr[j]; arr[j] = temp; } } // Put the datum element in the middle position (datum homing) arr[left] = arr[i]; arr[i]= base; // Recursion continues with a quick sort on the left and right sort(arr,left,i -1); sort(arr,i+1,right); } //Traversal of array public static void print(int[] arr){ for(int a : arr){ System.out.println(a); } } }
Select sort
Selective sorting is a simple and intuitive sorting algorithm. Principle: find the smallest (largest) element in the unordered array and exchange it with the element in the first position
Select the difference between sorting and bubble sorting:
Bubble sorting places the current largest element at the last position by exchanging the positions of two adjacent elements at a time. Select sorting. Remember the position of the smallest element every time you traverse. Finally, you can put the element in the appropriate position by exchanging it only once.
Thought:
1 array sorting, the array is unordered
2 first sorting: find the largest element from n-1 elements and exchange it with the first element
3 and so on
public class SelectSort { public static void main(String[] args) { int[] arr ={3,15,2,6,4,7,9,8}; for(int i = 0 ; i < arr.length;i++){ int minIndex= i;// Assume that the first element is the smallest, and use minIndex to record the location of the smallest element for(int j = i + 1; j < arr.length;j++){ if(arr[j] < arr[minIndex]){//Find an element smaller than the assumed minimum element minIndex = j;// Record the location of the smallest element } } // Find the smallest element and exchange the position of the smallest element with the first element if(minIndex != i){ int temp = arr[i]; arr[i]= arr[minIndex]; arr[minIndex] = temp; } } // Traversal array for(int a : arr){ System.out.println(a); } } }
Arrays tool class
Array tool class java uti. Arrays
There are no methods for us to call the array object itself, but the API provides a tool class Arrays for us to use, so we can perform some basic operations on the data object.
View JDK help documentation
The methods in the Arrays class are static methods decorated with static. When using them, you can call them directly with the class name instead of using the object (Note: it is "no" instead of "no")
It has the following common functions:
Assign a value to the array: through the fill method.
Sort the array: sort in ascending order through the sort method.
Compare data: use the equals method to compare whether the element values in the array are equal.
Find array elements: binary search can be performed on the sorted array through the binarySearch method
public static void main(String[] args) { int[] arr ={2,24,4,43,222,456,64,32,211,2,3}; //Use the methods provided by Arrays to sort the array Arrays.sort(arr); //Traversal array for(int a : arr){ System.out.println(a); } }
public static void main(String[] args) { int[] arr ={2,24,4,43,222,456,64,32,211,2,3}; //Use the methods provided by Arrays to sort the array Arrays.sort(arr);//You must sort first int res = Arrays.binarySearch(arr,2); System.out.println(res);
import java.util.Arrays; public class ArraysDemo { public static void main(String[] args) { int[] arr ={2,24,4,43,222,456,64,32,211,2,3}; //Fill array /* public static void fill(int[] a, int fromIndex, int toIndex, int val) */ Arrays.fill(arr,3,6,100); //Traversal array // for(int a : arr){ // System.out.println(a); // } System.out.println(Arrays.toString(arr)); } }
m.out.println(a);
}
}
```java public static void main(String[] args) { int[] arr ={2,24,4,43,222,456,64,32,211,2,3}; //Use the methods provided by Arrays to sort the array Arrays.sort(arr);//You must sort first int res = Arrays.binarySearch(arr,2); System.out.println(res);
import java.util.Arrays; public class ArraysDemo { public static void main(String[] args) { int[] arr ={2,24,4,43,222,456,64,32,211,2,3}; //Fill array /* public static void fill(int[] a, int fromIndex, int toIndex, int val) */ Arrays.fill(arr,3,6,100); //Traversal array // for(int a : arr){ // System.out.println(a); // } System.out.println(Arrays.toString(arr)); } }