one. About the characteristics of arrays
1. In Java, there is boundary checking whether you use arrays or collections. If the operation is out of bounds, a RuntimeException will be obtained.
2. Arrays can only save specific types. Arrays can save native data types, but collections cannot. Collections do not process objects in specific types. They process all objects according to Object type. What is stored in the collection is the object's reference rather than the object itself.
3. The collection class can only save references to objects. Arrays can be created to directly save native data types, or to save references to objects. In the collection, you can use Wrapper Class, such as Integer, Double, etc. to save native data type values.
Example code:
int a = 10; Integer integer = new Integer(a); int b = integer.intValue(); System.out.println(a = b);
4. The object array and the native data type array are almost the same in use; the only difference is that the object array saves references, and the native data type array holds the value of the native data type.
2. Correct use of arrays
If you need to store a large amount of data, for example, if you need to read 100 numbers, you need to define 100 variables. Obviously, it doesn't make much sense to repeat the code 100 times. How to solve this problem? Java language provides an array (array) data structure, which is a container that can store elements of the same data type and can store 100 numbers into an array. Arrays will be of great help at this time ~
1. Benefits of arrays
Is there any difference between storing data and not storing data? The biggest advantage of arrays is that they can automatically number all stored elements. Note that the number starts from 0. Easy to operate these data.
For example, the student number can be used to find the corresponding student.
2. Array format
Format 1:
Element type[] array name = new element type[number of elements or array length];
Example:
int[] arr = new int[5];arr[0] = 1;arr[1] = 2;
Format 2:
Element type[] array name = new element type[]{element, element,…};
int[] arr = new int[]{3,5,1,7}; int[] arr = {3,5,1,7};Note: When allocating space to an array, you must specify the number of elements that the array can store to determine the array size. The size of the array cannot be modified after creating the array. You can use the length attribute to get the size of the array.
3. Declare array variables
In order to use an array, the array must be declared in the program and the element type of the array must be specified.
=Left half:
First write the left side to clarify that the element type is int and the container uses an array. So how do you identify the array? .Then use a special symbol [] brackets to represent it. To use an array, you need to give the array a name, so we name the array x here. Then follow the equal sign.
Code reflects:
int [] x
Note: int x[] is also a format for creating arrays. It is recommended to declare arrays int [] x.
4. Create an array
= Right half:
To use a new keyword, called new. new is used to generate a container entity in memory. Data storage requires space. The space for storing a lot of data is opened with the new operator. new int[3]; this 3 is the number of elements. The part on the right defines a real array in memory that can store 3 elements.
new int[3] does two things. First, use new int[3] to create an array, and then assign the reference to the array variable x.
int [] x=new int[3];
What type is x?
Any variable must have its own data type. Note that this x is not of type int. int represents the type of element in the container. Then x is of array type.
An array is a separate data type. Data types are divided into two major schools, which are divided into basic data types and reference data types. The second largest school is the reference data type. So you have now come into contact with one of the three types of referenced data. That is, the array type[] brackets represent the array.
int[] arr = new int[5]; What happens in memory?
When any program is running, it is necessary to open up space in memory.int[] arr = new int[5];What does this program look like in memory? This involves the space opened by the Java virtual machine when executing the program. So how much space does Java open up? Continue to learn the memory structure of java.
5. Array initialization
Method 1: Do not use operator new
int[]arr = { 1, 2, 3, 4, 5 };Method 2: Use operator new
int[] arr2 = new int[] { 1, 2, 3, 4, 5 };int[] arr3=new int[3];arr3[0]=1;arr3[1]=5;arr3[2]=6;If the operator new is not used in the array initialization. Note: The following writing method is incorrect.
int[] arr;arr={1,2,3,4,5};At this time, initializing the array, you must place declaration, creation, and initialization in one statement. Separating it will cause syntax errors.
So you can only write as follows:
int[] arr={1,2,3,4,5};6. Array traversal
public static void main(String[] args) {int[] x = { 1, 2, 3 };for (int y = 0; y < 3; y++) {System.out.println(x[y]);// System.out.println("x["+y+"]="+x[y]); Print effect x[0]=1;} // Then this is the first common operation of arrays. traversal}There is an attribute in the array that can obtain the number of elements in the array, that is, the length of the array. The array name.length
public static void main(String[] args) {int[] x = { 1, 2, 3 };for (int y = 0; y < x.length; y++) {System.out.println(x[y]);// System.out.println("x["+y+"]="+x[y]); Print effect x[0]=1;} // Then this is the first common operation of arrays. traversal}7. Common exceptions of arrays
An array corner marker crosses the bounds exception: Note: The angle marker of the array starts from 0.
public static void main(String[] args) {int[] x = { 1, 2, 3 };System.out.println(x[3]);//java.lang.ArrayIndexOutOfBoundsException}Two-null pointer exception:
public static void main(String[] args) {int[] x = { 1, 2, 3 };x = null;System.out.println(x[1]);// java.lang.NullPointerException}Array:
When to use arrays: When there are many elements, in order to facilitate operation of these arrays, temporary storage will be performed first, and the container used is an array.
Features:
The array length is fixed.
8. Common operations of arrays
1: Case:
An array takes out the maximum value
/*Define a function to get the maximum value:
1. Determine the result: return value type int
2. Unknown content: The maximum value of which array is not determined, then the array is not determined.
Ideas:
1. Define a variable and record the larger elements of the array.
2. Iterate through the entire array and compare each element of the array with the variable.
3. When a variable encounters an element larger than it, let the variable record the value of the element. When the loop ends, the maximum value is generated.
*/public static int getMax(int[] arr){//Define the variable to record a larger value and initialize it to any element in the array. int max = arr[0];for(int x=1; x<arr.length; x++){if(arr[x]>max)max = arr[x];}return max;}Two: Direct sorting
Case 2: Sort arrays using direct sort:
/*
Select Sort.
Compare the elements with one corner to other elements.
At the first end of the inner loop, the most value appears at the head angle position.
*/public static void selectSort(int[] arr){for(int x=0; x<arr.length-1; x++){for(int y=x+1; y<arr.length; y++)//Why is the initialization value of y x+1? Because every time you compare, // is compared with the next element marked on the x corner. {if(arr[x]>arr[y]){int temp = arr[x];arr[x] = arr[y];arr[y] = temp;}}} }Three: Bubble sorting
/*Bubbling sort. Comparison method: Compare two adjacent elements. If the conditions are met, position replacement will be performed. Principle: The inner loop ends once, and the most value appears at the tail corner position. */public static void bubbleSort(int[] arr){for(int x=0; x<arr.length-1; x++){for(int y=0; y<arr.length-x-1; y++)//-x: Let the meta-deductance of each participation in the comparison. //-1: Avoid corner marks crossing boundaries. {if(arr[y]>arr[y+1]){int temp = arr[y];arr[y] = arr[y+1];arr[y+1] = temp;}}}}Four: Half-fold search (dual-particle method)
/*In order to improve search efficiency, you can use the half-finish search method. Note: This search is only valid for ordered arrays. This method has also become a binary search method. */public static int halfSeach(int[] arr,int key){int min,mid,max;min = 0;max = arr.length-1;mid = (max+min)/2;while(arr[mid]!=key){if(key>arr[mid])min = mid + 1;else if(key<arr[mid])max = mid - 1;if(min>max)return -1;mid = (max+min)/2;}return mid;}Five: Array flip
/*Inversion is actually the positional replacement of the elements of the head and tail corner marks, and then the head corner marks are automatically increased. The tail corner mark is self-decreased. When the head angle mark is < tail angle mark, the substitution action can be performed. */public static void reverseArray(int[] arr){for(int start=0,end=arr.length-1; start<end; start++,end--){swap(arr,start,end);}}// Perform positional displacement of elements of the array. public static void swap(int[] arr,int a,int b){int temp = arr[a];arr[a] = arr[b];arr[b] = temp;}11. Two-dimensional array
Use of Arrays
Detailed explanation of Java arrays
traversal: toString() Returns the elements of the array as a string
Sort: sort() Order the array in ascending order
Search: binarySearch() searches for the specified element in the specified array, returns the index of the element. If no return is found (-insert point-1) Note: When using the search function, the array must be sorted first.
Two-dimensional array:
Smoking:
Don't have money to buy 1 variable
A little money is a pack of one-dimensional array 20 variables
Very rich 10 packs (two-dimensional array) 2D array
Two-dimensional array: In essence, storage is a one-dimensional array.
Array definition:
Array type[][] Array name = new array type[number of one-dimensional array][number of elements in each one-dimensional array];
Detailed explanation of Java arrays
Question: Why a.length = 3, a[0].length = 4?
Detailed explanation of Java arrays
Initialization of array:
Static initialization:
int [][] a = new int[][]{ {12,34,45,89},{34,56,78,10},{1,3,6,4} };
Dynamic initialization:
Detailed explanation of Java arrays
Common operations for two-dimensional arrays:
1. Traverse a two-dimensional array
2. Summarize two-dimensional arrays
class Demo3 { // Define a functional function that traverses a two-dimensional array public static void printArr2( int [][] a ){ // 1. Disassemble the two-dimensional array for ( int i = 0 ; i < a.length ; i++ ) { // 2. Disassemble the one-dimensional array to obtain data for ( int j = 0 ; j < a[i].length ; j++ ) {System.out.print( a[i][j]+" ," ); } }} // Define a function to calculate the accumulation sum of elements in a two-dimensional array public static long getSum( int [][] a ){ // 0. Define a result variable long sum = 0L; // 1. Disassemble the two-dimensional array for ( int i = 0 ; i < a.length ; i++ ) { // 2. Disassemble the one-dimensional array to obtain data for ( int j = 0 ; j < a[i].length ; j++ ) {sum+=a[i][j]; } } return sum;} // Statistics the number of elements in a two-dimensional array public static int getDataCount( int [][] a ){ // 0. Record the number of elements int count = 0; // 1. Disassemble the two-dimensional array for ( int i = 0 ; i < a.length ; i++ ) { // 2. Disassemble the one-dimensional array to obtain data for ( int j = 0 ; j < a[i].length ; j++ ) {count++; } } return count;} public static void main(String[] args) {int [][] a = new int[][]{ {23,4,5},{2},{4,5,78,56,90} };printArr2( a ); System.out.println();System.out.println("Accumulated sum is: "+getSum( a ) );System.out.println("Statistical number of elements: "+getDataCount( a ) );System.out.println("Hello World!");}}The above are all the topics about java arrays. As you can see, java arrays are a very powerful data structure.