catalogue
2, Array as an argument to the method
4. Get familiar with JVM memory area division
3, Array as the return value of the method
three Arrays.copyOfRange for copying
4. Copy through System.arraycopy
2. Average the elements in the array
3. Find the specified element in the array
4. Check the order of the array
1, Basic usage of arrays
1. What is an array
Array: a collection that stores a set of data of the same data type
Essence: it allows us to "batch" create variables of the same type
For example, if we create an integer variable, we can use int a = 1; Then, if you create multiple integer variables, you can use the array int [] array = {...}
Note: it should be noted that in Java, the variables stored in the array must be of the same type!!
2. Create an array
dynamic initialization
Basic syntax: data type [] array name = new data type [] {initialization data};
Let's take an example to further understand:
public class TestDemo { public static void main(String[] args) { int[] array = new int[]{1,2,3,4,5}; } }
initiate static
Basic syntax: data type [] array name = {initialization data};
Similarly, let's take an example:
public class TestDemo { public static void main(String[] args) { int[] array2 = {1,2,3,4,5,6}; } }
It should be noted that during static initialization, the number of array elements is consistent with the format of initialization data
3. Basic use of array
Get array length
public class TestDemo { public static void main(String[] args) { int[] array = new int[]{1,2,3,4,5}; System.out.println("length:"+array.length); } }
The length of the array can be obtained by using array.length“ . " This operation is a member access operator, which will be often used in object-oriented later
Accessing array elements
public class TestDemo { public static void main(String[] args) { int[] array = new int[]{1,2,3,4,5}; System.out.println(array[0]); System.out.println(array[1]); System.out.println(array[2]); System.out.println(array[3]); System.out.println(array[4]); } }
1. Press [] to mark array elements. It should be noted that the subscript counts from 0, so the subscript access operation cannot exceed the valid range [0, length - 1]. If it exceeds the valid range, the subscript out of range exception will occur
2. Use [] to read and modify data
Traverse array elements
Method 1: use the for loop to traverse the array elements
public class Demo { public static void main(String[] args) { int[] array = {1,2,3,4,5}; for (int i = 0; i <= array.length-1 ; i++) { System.out.print(array[i]+" "); } } }
Method 2: use the for each loop to traverse the array elements
For each loop: also known as enhanced for loop, it is another way to use the for loop. It can more conveniently complete the traversal of the array and avoid the wrong writing of loop conditions and update statements. However, the for each loop can not get the subscript and is used more in the collection
public class Demo { public static void main(String[] args) { int[] array = {1,2,3,4,5}; for (int x : array) { System.out.print(x+" "); } } }
Print array as string
If we want to print an array, how can we print it besides writing a printing method? First, let's try to print it directly. The printed result is:[ I@1b6d3586 Obviously, this is not what we want. Direct printing does not work. At this time, we need to output the array of parameters in the form of string with the help of Java's tool class Arrays.toString
import java.util.Arrays;//Import array tool class package public class Demo { public static void main(String[] args) { int[] array = {1,2,3,4,5}; System.out.println(Arrays.toString(array)); } }
2, Array as an argument to the method
1. Basic usage
public class Demo { public static void printArray(int[] a){ for (int x : a) { System.out.print(x+" "); } } public static void main(String[] args) { int [] array = {1,2,3,4,5}; printArray(array); } }
Here, you can see that int [] a is a formal parameter and int [] array is an argument
2. Understand reference types
Transfer built-in type
public class Demo2 { public static void func(int x){ x = 10; System.out.println("x:"+x); } public static void main(String[] args) { int num = 20; func(num); System.out.println("num:"+num); } }
We found that modifying the value of formal parameter x does not affect the value of argument num!
Pass reference type
//Take the transport group as an example public class Demo3 { public static void exchange(int[] array){ int temp = array[0]; array[0] = array[1]; array[1] = temp; } public static void main(String[] args) { int[] array ={1,2,3,4,5}; System.out.println("Before exchange:"); System.out.println("array[0]="+array[0]+",array[1]="+array[1]); exchange(array); System.out.println("After exchange:"); System.out.println("array[0]="+array[0]+",array[1]="+array[1]); } }
Through this running result, we can find that the value of the variable can be modified by passing the parameter with the array as the parameter. Why?
1. Originally, the array at this time is a reference variable, in which the address of the variable is stored.
2. The reference refers to the object. As mentioned earlier, the object is stored on the heap! You can get the address on the heap in Java!
Next, make a specific analysis through the figure to help understand:
Notes on References:
1. Does the reference must be on the stack? It depends on the nature of the variable. If it is a local variable, it must be on the stack. If it is an instantiated member variable, it is not necessarily
2. Can a reference point to multiple objects at the same time? No! A reference can only have one object!
three Know null
Null: Represents "null reference" in Java, That is, an invalid reference
Next, let's feel it through the code
public class Demo4 { public static void exchange(int[] array){ int temp = array[0]; array[0] = array[1]; array[1] = temp; } public static void main(String[] args) { int[] array = {1,2,3,4,5}; exchange(null); } }
When the code runs incorrectly, let's analyze the causes and solutions
When passing a reference, null will report a null pointer exception. The function of null is similar to null in C language. They all represent an invalid memory location, so no reading operation can be performed
4. Get familiar with JVM memory area division
The next figure shows you the JVM partition in detail
Here is a supplement to the Native method: JVM is a program implemented based on C + +. In the process of Java program execution, it is essentially necessary to call some functions provided by C + + to interact with the underlying operating system. Therefore, some functions implemented in C + + will also be called in Java development. The Native method here refers to these functions implemented in C + + and then called by Java Function of
3, Array as the return value of the method
Let's write a method to multiply all array elements by 2
import java.util.Arrays; public class Demo4 { public static void transform(int[] array) { for (int i = 0; i < array.length; i++) { array[i] = array[i] * 2; } } public static void main(String[] args) { int[] array = {1,2,3,4,5}; transform(array); System.out.println(Arrays.toString(array)); } }
There is no problem with this writing, but it will destroy the original array. If we don't want to destroy the original array, how should we write it? At this time, we need to create a new array inside the method and return the array. Next, let's see the specific code implementation
import java.util.Arrays; public class Demo4 { public static int[] transform(int[] array) { int[] array2 = new int[array.length]; for (int i = 0; i < array.length; i++) { array2[i]=2*array[i]; } return array2; } public static void main(String[] args) { int[] array = {1,2,3,4,5}; int[] ret = transform(array);//Create an array to receive array2 System.out.println(Arrays.toString(array)); System.out.println(Arrays.toString(ret)); } }
At the same time, because the array is a reference type, only the first address of the array is returned to the function caller, The array contents are not copied, which is more efficient
4, Copy of array
1.for loop copy
import java.util.Arrays; public class Demo5 { public static int[] copyArray(int[] array){ int[] copy = new int[array.length];//Defines the size of an array for (int i = 0; i < array.length; i++) { copy[i] = array[i]; } return copy; } public static void main(String[] args) { int[] array = {1,2,3,4,5}; System.out.println(Arrays.toString(copyArray(array))); } }
2. Copy arrays.copyof
Let's learn about the function and usage of copyOf through the help manual: copyOf (array to be copied, length of copy)
Next, it is implemented by code
import java.util.Arrays; public class Demo5 { public static void main(String[] args) { int[] array = {1,2,3,4,5}; int[] ret = Arrays.copyOf(array,array.length); System.out.println(Arrays.toString(ret)); } }
three Arrays.copyOfRange for copying
Copy parts through Arrays.copyOfRange
public class Demo5 { public static void main(String[] args) { int[] array = {1,2,3,4,5}; int[] ret = Arrays.copyOfRange(array,0,5); System.out.println(Arrays.toString(ret)); } }
I believe it must be a little confused to see that the subscript is 5 and does not cross the boundary, This is because Java's from and to are both closed on the left and open on the right. Here to 5 is equivalent to < 5, that is, get 4 here!
4. Copy through System.arraycopy
When copying with Arrays.copyOf, move the cursor to Arrays.copyOf and press ctrl to get
It is found that Arrays.copyOf calls System.arraycopy. Hold down ctrl and click System.arraycopy to analyze the usage
import java.util.Arrays; public class Demo5 { public static void main(String[] args) { int[] array = {1,2,3,4,5}; int[] copy = new int[array.length]; System.arraycopy(array,0,copy,0,array.length); System.out.println(Arrays.toString(copy)); } }
5. Copy through array.clone()
As like as two peas, the.clone() will produce a copy of the same content as the original array.
import java.util.Arrays; public class Demo6 { public static void main(String[] args) { int[] array = {1,2,3,4,5}; int[] copy = array.clone(); System.out.println(Arrays.toString(copy)); } }
6. Deep and shallow copies
First, let's understand the concepts of these two:
Deep copy: modifying the copied array will not affect the original array
Shallow copy: modifying the copied array will affect the original array
Summary: to achieve deep copy, you need to copy the object itself. The examples we have just given are all deep copies.
If the array contains basic data types, it is a deep copy. If the array is a reference type, it is a shallow copy.
5, Array classic exercises
Review the old and know the new. Next, we provide some classic exercises for readers to practice. At the same time, we attach the author's solution. If there are errors, please correct them!
1. Find the largest element
Given an integer array, find the largest element (the same is true for finding the smallest element)
public class Test1 { public static void findMax(int[] array){ int max = array[0];//Find from 0 subscript for (int i = 0; i < array.length; i++) { if(array[i]>max){ max = array[i]; } } System.out.println(max); } public static void main(String[] args) { int[] array = {1,5,7,9,11}; findMax(array); } }
2. Average the elements in the array
Given an integer array, find the average
public class Test2 { public static double average(int[] array){ int sum = 0; for (int i = 0; i < array.length; i++) { sum += array[i]; } double num = (double)sum/(double)array.length; return num; } public static void main(String[] args) { int[] array = {1,2,3,4,5}; System.out.println(average(array)); } }
3. Find the specified element in the array
Given an array and an element, find the position of the element in the array
Sequential search
public class Test3 { public static int find(int[] array,int toFind){ for (int i = 0; i < array.length; i++) { if (array[i] == toFind){ return i; } } return -1;//Indicates not found } public static void main(String[] args) { int[] array = {1,2,3,4,5,6}; System.out.println(find(array,5)); } }
Binary search
One defect of binary search is that it can only find arrays in ascending or descending order. Next, take ascending order as an example
public class Test4 { public static int binarySearch(int[] array,int toFind){ int left = 0; int right = array.length-1; while(left<=right){ int mid =(right+left)/2; if(toFind>array[mid]){//Find it in the right half and narrow it down left = mid+1; }else if(toFind<array[mid]){//Find it in the left half and narrow it down right = mid-1; }else{ return mid; } } return -1; } public static void main(String[] args) { int[] array = {1,2,3,4,5,6}; System.out.println(binarySearch(array,2)); } }
4. Check the order of the array
Given an integer array, determine whether the array is ordered (ascending)
public class Test5 { public static boolean func(int[] array){ for (int i = 0; i < array.length; i++) { if(array[i]<array[i+1]){ return true; } } return false; } public static void main(String[] args) { int[] array = {1,2,3,4,5}; System.out.println(func(array)); } }
5. Array sorting
Given an array, let the array be sorted in ascending (descending) order
Bubble sorting
import java.util.Arrays; public class Test6 { public static void bubbleSort(int[] array){ for (int i = 0; i < array.length; i++) { for (int j = 0; j < array.length-1-i ; j++) { if(array[j]>array[j+1]){ int temp = array[j+1]; array[j+1] = array[j]; array[j] = temp; } } } } public static void main(String[] args) { int[] array = {1,8,9,5,4}; bubbleSort(array); System.out.println(Arrays.toString(array)); } }
Arrays.sort
Bubble sorting performance is low. A more efficient sorting algorithm is built in Java: Array.sort
import java.util.Arrays; public static void main(String[] args) { int[] array = {1,8,9,5,4}; Arrays.sort(array); System.out.println(Arrays.toString(array)); } }
6. Array reverse order
Given an array, arrange the elements in reverse order
Idea: give two subscripts to point to the first element and the last element respectively, exchange the two elements, and then realize self increase and self decrease. Repeat the operation until you reach the middle of the array
import java.util.Arrays; public class Test7 { public static void reverse(int[] array){ int left = 0; int right = array.length-1; while(left < right){ int temp = array[left]; array[left] = array[right]; array[right] = temp; left++; right--; } } public static void main(String[] args) { int[] array = {1,2,3,4,5}; reverse(array); System.out.println(Arrays.toString(array)); } }
7. Array number arrangement
Given an integer array, put all even numbers in the first half and all odd numbers in the second half of the array
Basic idea: set two subscripts to point to the first element and the last element respectively. Use the previous subscript to find the first odd number from left to right, use the latter subscript to find the first even number from right to left, and then exchange the elements at two positions. Cycle in turn
import java.util.Arrays; public class Test8 { public static void transform(int[] array){ int left = 0; int right = array.length-1; while(left < right){ while(left<right && array[left]%2==0){ left++;//If it is an even number, judge the next element } while(left<right && array[right]%2!=0){ right--;//If it is an odd number, judge the next element } //Swap odd and even numbers int temp = array[left]; array[left] = array[right]; array[right] = temp; } } public static void main(String[] args) { int[] array = {1,2,6,8,9,7}; transform(array); System.out.println(Arrays.toString(array)); } }
6, Two dimensional array
1. Basic grammar
Data type [] [] array name = new data type [number of rows] [number of columns] {initialization data};
Two dimensional arrays in Java can omit columns, not rows
int[][]array = {{1,2,},{3,4},{5,6}}; int[][]array2 = new int[3][2]; int[][]array3 = new int[][]{{1,2,},{3,4},{5,6}};
2. Code example
public class TestDemo { public static void main(String[] args) { int[][] arr = { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12} }; for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[i].length; j++) { System.out.printf("%d\t", arr[i][j]); } System.out.println(""); } } }
3. Specific usage
The specific usage of two-dimensional array is similar to that of one-dimensional array, which will not be repeated here