Java Array
1. Definition of arrays
An array is an ordered collection of data of the same type Arrays describe several data of the same type, grouped in a sequence Where each data is called an array element, and each array element can be accessed through a subscript
1.1, Array declaration creation
-
Array variables must be declared before they can be used in programs.
dataType[] arrayRefVar; //Be the first choice dataType arrayRefVar[]; //Same results, but not preferred
-
The Java language uses the new operator to create arrays with the following syntax
dataType[] arrayRefVar = new dataType[arraySize]; //int[] nums=new int[10]
-
The elements of an array are accessed through an index, which starts at 0
-
Get the length of the array: arrays.length
int[] nums; //1. Declare an array nums = new int[3]; //2. Create an array //3. Assigning values to array elements nums[0]=1; nums[1]=2; nums[2]=3; for (int num : nums) { //Print all elements of an array System.out.println(num); }
1.2. Memory analysis
1.3, three initializations of arrays
-
initiate static
//Static Initialization: Create + Assign int[] a={1,2,3}; Man[] mans={new Man(1,1),new Man(2,2)}
-
dynamic initialization
//Include default initialization int[] a=new int[2]; //Default value is 0 a[0]=1; a[1]=2;
-
Default Initialization
An array is a reference type whose elements correspond to instance variables of a class, so once the array is allocated space, each element of the array is implicitly initialized in the same way as the instance variable.
1.4. Basic characteristics of arrays
- Its length is fixed, and once an array is created, its size cannot be changed.
- Its elements must be of the same type, and mixed types are not allowed.
- Elements in an array can be of any data type, including basic and reference types.
- Array variables are of reference type, and arrays can also be considered objects, where each element corresponds to a member variable of the object.
- Arrays are objects themselves, and objects in Java are in the heap, so the array itself is in the heap, whether it holds the original type or other object types.
1.5, Array Boundary
Legal interval of subscript:[0, length-1],Error will be reported if the boundary is crossed;
public static void main(String[] args) { int[] a=new int[2]; system.out.println(a[2]); }
ArraylndexOutOfBoundsException:ArrayIndexOutOfBoundsException!
Summary:
- Arrays are arrays of ordered sets of the same data type (data types can be any type) and are objects.
- An array element is equivalent to a member variable of an object
- The length of the array is fixed and immutable.If out of bounds, report: ArraylndexOutofBounds
2. Use of arrays
2.1, For-Each cycle
int[] arrays = {1,2,3,4,5}; //Print all array elements JDK1.5 without Subscripts for (int array : arrays) { System.out.println(array); }
2.2. Array Make Method Input
//Print array elements public static void printArray(int[] a){ for (int i = 0; i < a.length; i++) { System.out.print(a[i]+" "); } }
2.3, Array as return value
//Invert Array public static int[] reverse(int[] arrays){ int[] result = new int[arrays.length]; //Reversed operation for (int i = 0; i < arrays.length; i++) { result[i] = arrays[arrays.length-i-1]; } return result; }
3. Multidimensional Arrays
Multidimensional arrays can be viewed as arrays, for example, two-dimensional arrays are special arrays, each element of which is a one-dimensional array.
int arr[][] = new int[3][2]; //Two-dimensional array, three rows and two columns
int[][] array = {{1,2},{3,4},{5,6}}; //Print all elements of a two-dimensional array for (int i = 0; i < array.length; i++) { //arrays.length=3 for (int j = 0; j < array[i].length; j++) { System.out.print(array[i][j]+" "); } System.out.println(); }
4. Arrays Classes
- Array's tool class java.util.Arrays
- Since there is no way to use the array object itself, the API provides a tool class, Arrays, for us to use.
- Methods in Array classes are static methods decorated with static, which can be invoked directly using the class name instead of using the object.
- Common Functions
- Assigning a value to an array: the fill method.
- Sort: sort method, ascending.
- Compare arrays: The equals method compares whether the element values in the array are equal.
- Find array elements: BiarySearch performs a binary search on sorted arrays.
int[] a = {1,2,3,4,9000,32145,451,21}; System.out.println(a); // [I@28d93b30 (hashcode) //Arrays.toString Prints Array Elements System.out.println(Arrays.toString(a)); //[1, 2, 3, 4, 9000, 32145, 451, 21] //Bisection Find a Value Return Subscript System.out.println(Arrays.binarySearch(a, 9000)); // 4 //Fill Arrays.fill(a,2,4,0); //Fill 0 between arrays [a[2]~a[4] System.out.println(Arrays.toString(a)); //[1, 2, 0, 0, 9000, 32145, 451, 21] //Sort ascending Arrays.sort(a);
5. Bubble Sorting
1. Bubble sorting is the most famous sorting algorithm among the eight major sorting categories.
2. Code: Two layers of circulation, the number of foaming wheels on the outside and the comparison of the inner layers in turn.
3. When we see nested loops, we should be able to see that the time complexity of this algorithm is O(n2).
//Bubble sort //1. Compare the two adjacent elements in an array and swap their positions if the first number is greater than the second number //2. Each comparison produces a maximum or minimum number (ascending to maximum) //3. You can sort less once in the next round //4. Loop in turn until the end public static int[] sort(int[] array){ int temp=0; //Outer loop, number length-1 for (int i = 0; i < array.length-1; i++) { //Inner loop: If the first number is greater than the second number, swap their positions for (int j = 0; j < array.length-1-i; j++) { if(array[j]>array[j+1]){ temp=array[j]; array[j]=array[j+1]; array[j+1]=temp; flag = true; } } } return array; } public static void main(String[] args) { int[] a={8,1,35,47,19,-2}; int[] sort = sort(a); System.out.println(Arrays.toString(sort)); //[-2, 1, 8, 19, 35, 47] }
optimization
//Bubble sort algorithm int[] a = {6,2,4,5,2,1,3}; int temp = 0; for(int i = 0;i<a.length-1;i++){ boolean flag = false; for(int j = 0;j<a.length-1-i;j++){ if(a[j] > a[j+1]){ temp = a[j]; a[j] = a[j+1]; a[j+1] = temp; flag = true; } } } if(!flag){ break; } System.out.println("The sorted result is:"); for(int i : arr){ System.out.print(i); }
6. Sparse Array
Sparse numbers can be used when most of the elements in an array are zero or are arrays of the same value
- Groups are handled to hold sparse arrays of that array:
-
The record array has rows, columns, and different values
-
Reduce program size by recording elements, rows, columns, and values with different values in a small array
-
The following image shows the original array on the left and the sparse array on the right
-
Requirements: In the writing of Gobang games, there is the ability to save out and resume the board
Analytical Problem: Because many values of this two-dimensional array are the default value of 0, a lot of meaningless data has been recorded.
Solution: Sparse Array
//Create a two-dimensional array of 11*11 0: no pieces, 1: black 2: white int[][] array1 = new int[11][11]; array1[1][2] = 1; array1[2][3] = 2; //Output original array System.out.println("Original array:"); for (int[] array : array1) { for (int i : array) { System.out.print(i+"\t"); } System.out.println(); } //Convert to Sparse Array Save //1. Number of valid values int sum = 0; //Total Valid Values for (int i = 0; i < 11; i++) { for (int j = 0; j < 11; j++) { if(array1[i][j]!=0){ sum++; } } } //2. Create a sparse array int[][] array2 = new int[sum+1][3]; array2[0][0] = 11; array2[0][1] = 11; array2[0][2] = sum; //3. Traverse a two-dimensional array to store valid values in a sparse array int count = 0; for (int i = 0; i < array1.length; i++) { for (int j = 0; j < array1[i].length; j++) { if(array1[i][j]!=0){ count++; array2[count][0] = i; array2[count][1] = j; array2[count][2] = array1[i][j]; } } } //4. Output Sparse Array System.out.println("Sparse array:"); for (int i = 0; i < array2.length; i++) { for (int j = 0; j < array2[i].length; j++) { System.out.print(array2[i][j]+"\t"); } System.out.println(); } /* Result: Output original array 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 Sparse Array 11 11 2 1 2 1 2 3 2 */
Video Learning Address: https://www.bilibili.com/video/BV12J41137hu?p=51