catalogue
2, Array as an argument to a method
1. Get familiar with JVM memory area division
4. Array as the return value of the method
3. Allocate elements for integer arrays
4. Find the specified element in the integer array (binary search)
1, Basic usage of array
1. What is an array
Array essentially allows us to "batch" create variables of the same type. In Java, the variables contained in the array must be of the same type
2. Creation of array
3. Use of arrays
(1) The length of the array can be obtained by using arr.length. “.” This operation is a member access operator
(2) Press [] to mark array elements Note that the subscript counts from 0
(3) Use [] to read and modify data
(4) The subscript access operation cannot exceed the valid range [0, length - 1]. If it exceeds the valid range, the subscript out of bounds exception will appear Lang. ArrayIndexOutOfBoundsException (description in IIEA)
(5) Traversal array:
import java.util.Arrays;//Method three public class Array{ public static void main(String[] args){ int[] arr = {1, 2, 3}; //Method 1: for loop for(int i = 0; i < arr.length; i++){ System.out.print(arr[i]+" "); } //Method 2: for each loop (enhanced for loop) for each loop can't get the subscript. For loop can get the subscript. For each loop is more used in the set for(int i : arr){ System.out.print(arr[i]+" "); } //Method 3: with the help of Java's tool class Arrays for manipulating Arrays System.out.println(Arrays.toString(arr));//toString: output the array of parameters as a string }
2, Array as an argument to a method
1. Get familiar with JVM memory area division
2. One question:
public class Test{ public static void func1(int[] array){ array = new int[]{11, 2, 13, 4, 51, 61}; } public static void func2(int[] array){ array[0] = 899; } public static void main2(String[] args) { int[] array = {1, 2, 3, 4, 5, 6}; System.out.print(Arrays.toString(array)); System.out.println(); func1(array); System.out.print(Arrays.toString(array)); System.out.println(); func2(array); System.out.print(Arrays.toString(array)); } }
Tips: (1)func1(array); At this point, the array name "array" is a "reference" When parameters are passed, they are passed by reference, which is also called passing by value, but the value is just an address
(2) reference is equivalent to an "alias", which can also be understood as a pointer. The so - called "reference" is essentially just an address Java sets the array as a reference type. In this case, the subsequent array parameter transfer is actually just to pass the address of the array into the function parameter This can avoid copying the whole array (the array may be long, so the copying cost will be great)
Compile and run the code, and the output is as follows:
1 2 3 4 5 6
1 2 3 4 5 6
899 2 3 4 5 6
The analysis is as follows:
3.null
4. Array as the return value of the method
For example, we need to write a method to * 2 each element in the array (two ways to implement the code)
Method 1:
public class Test { public static void main(String[] args) { int[] arr = {1, 2, 3}; transform(arr); for(int i : arr){ System.out.print(i + " "); } } public static void transform(int[] arr) { for (int i = 0; i < arr.length; i++) { arr[i] = arr[i] * 2; } } }
This implementation method is not impossible. It just destroys the original array. If you don't want to destroy the original array, you need to create a new array inside the method and return it by the method
Method 2:
public class Test { public static void main(String[] args) { int[] arr = {1, 2, 3}; transform(arr); for(int i : ret){ System.out.print(i + " "); } } public static int[] transform(int[] arr) { int[] ret = new int[arr.length]; for (int i = 0; i < arr.length; i++) { ret[i] = arr[i] * 2; } return ret; } }
3, Some exercises of array
1. Array to string
(1) First, let's get to know the "package":
import java.util.Arrays public class Test { public static void main(String[] args) { int[] arr = {1,2,3,4,5,6}; String newArr = Arrays.toString(arr); System.out.println(newArr); } }
Compile and run the code, and the output is as follows:
[1,2,3,4,5,6]
In fact, we can also simulate the implementation of toString(int[] a):
public class Test{ public static String myToString(int[] array){ if(array == null){ return null; }//Note that if a null pointer is passed String str = "["; for(int i = 0; i < array.length; i++){ str = str + array[i]; if(i != array.length - 1){ str = str +",";// Except for the last element, all other elements should be followed by "," } } str = str + "]"; return str; } public static void main6(String[] args) { int[] array = {1, 2, 3, 4, 5, 6}; String ret = myToString(array); System.out.println(ret); } }
2. Copy of array
(1) Method 1:
The method copy. In the Arrays class Of (int [] original, int newlength), the return value is static int []. This method is for integer Arrays and can copy Arrays:
(arrays of other data types can be modified based on the above, such as floating-point array copy.Of(float[] original,int newlength), and the return value is static float []...)
import java.util.Arrays public class Test{ public static void main(String[] args){ int[] array = {1, 2, 3, 4, 5, 6}; int[] ret = Arrays.copyOf(array,array.length*2); System.out.println(Arrays,toString(ret)); } }
Compile and run the program, and the output is as follows:
[1,2,3,4,5,6,0,0,0,0,0,0]
In fact, you can also limit the copy of the range. This requires the method copyOfRange(int[] original,int from,int to)
① original: source array
② from: where to start copying
③ to: end copy location
Note that the range is [from, to], closed on the left and open on the right
import java.util.Arrays public class Test{ public static void main(String[] args){ int[] array = {1, 2, 3, 4, 5, 6}; int[] ret = Arrays.copyOfRange(array,1,3); System.out.println(Arrays,toString(ret)); } }
Compile and run the code, and the output is as follows:
[2,3]
(2) Method 2:
Use the for loop to copy the elements in the array one by one
import java.util.Arrays; public class Test{ public static int[] myCopy(int[] array,int newlength){ int[] copy = new int[newlength]; for(int i = 0; i < newlength; i++){ copy[i] = array[i]; } return copy; } public static void main(String[] args){ int[] array = {1, 2, 3, 4, 5}; int newlength = 3; int[] ret = myCopy(array,newlength); System.out.println(Arrays.toString(ret)); } }
(3) Method 3:
The method arraycopy in the System class (object SRC, int srcpos, object DeST, int destpos, int length); The return value is static void
① src: source array
② srcPos: copy from the source array (subscript)
③ dest: target array
④ destPos: copy to this position of the target array (subscript)
⑤ Length: copy length
import java.util.Arrays public class Test{ public static void main(String[] args){ int[] array = {1, 2, 3, 4, 5, 6}; int[] copy = System.arraycopy(array,0,copy,0,array.length); System.out.println(Arrays,toString(copy)); } }
(4) Method 4:
Using method clone():
public class Test{ public static void main(String[] args){ int[] array = {1, 2, 3, 4, 5, 6}; int[] copy = array.clone();//Generate a copy System.out.println(Arrays,toString(copy)); } }
All four methods are shallow copies.
Shallow copy: shallow copy only copies the reference of an object, not the object itself. The old and new objects still share the same block of memory
Deep copy: deep copy will create an identical object. The new object and the original object do not share memory. Modifying the new object will not change the original object.
3. Allocate elements for integer arrays
We need to use the method fill(int[] a,int val) in the Arrays class, and the return value is static void
fill(int[] a,int fromIndex,int toIndex,int val), the return value is static void
① a: array to allocate elements
② fromIndex: the location (subscript) at which the allocation starts
③ toIndex: end allocation position (subscript)
④ val: value to assign
Attention range: [fromIndex,toIndex)
public class Test{ public static void main10(String[] args){ int[] array = new int[10]; Arrays.fill(array,2,6,66);//Fill 66 from [2,6) subscript System.out.println(Arrays.toString(array)); } }
4. Find the specified element in the integer array (binary search)
Unlike C language, java is very simple to implement binary search. It only needs to use the method binarySearch(int[] a,int key) in the Arrays class, and the return value is static int
public class Test{ public static void main(String[] args) { int[] array = {1, 2, 3, 4, 5, 6}; System.out.println(Arrays.binarySearch(array,9)); } }
Compile and run the code, and the output is as follows:
-7
Why -7? At this time, we will look at the source code to realize it
IV. two dimensional array
1. Basic grammar
public class Test{ public static void main(String[] args) { int[][] array = {{1, 2, 3},{4, 5, 6}}; //Method 1: for(int i = 0; i < array.length; i++){ for(int j = 0; j < array[i].length; j++){ System.out.print(array[i][j]+" "); } System.out.println(); } //Method 2: for(int[] ret : array){ for(int i:ret){ System.out.print(i+" "); } System.out.println(); } //Method 3: System.out.println(Arrays.deepToString(array));//[[1, 2, 3], [4, 5, 6]] } }
3. Two dimensional arrays in Java cannot omit rows; If the column is omitted, an error of null pointer exception will be reported, but there are also solutions
public class Test{ public static void main(String[] args){ int[][] array = new int[2][];//Lines cannot be omitted in java; You can't omit the error of the column (otherwise null pointer exception will be reported), but you can solve this error array[0] = new int[3]; array[1] = new int[2];//Irregular two-dimensional array for(int i = 0; i < array.length; i++){ for(int j = 0; j < array[i].length; j++){ System.out.print(array[i][j]+" "); } System.out.println(); } }