Array summary of JavaSE

Posted by ethridgt on Wed, 02 Feb 2022 18:01:57 +0100

catalogue

1, Basic usage of array

1. What is an array

2. Creation of array

3. Use of arrays

2, Array as an argument to a method

1. Get familiar with JVM memory area division

2. One question:

 3.null

 4. Array as the return value of the method

3, Some exercises of array

1. Array to string

2. Copy of array

3. Allocate elements for integer arrays

4. Find the specified element in the integer array (binary search)

IV. two dimensional array

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

(1) Dynamic initialization: data type [] array name = new data type [] {initialization data};  
new: a keyword that instantiates an object, which indicates that the array is an object
For example: int[] arr = new int[3]// An array with a length of 3 was created
       int[] arr = new int[]{1,2,3};// An array of length 3 is created and initialized to 1,2,3
(2) Static initialization: data type [] array name = {initialization data}; For example: int[] array = {1, 2, 3};
In fact, the array can also be written as int arr[] = {1, 2, 3}; This is more similar to C language However, we prefer to write in the form of int[] arr Int and [] are a whole

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

(1) Program counter (PC Register): It's just a small space , Save the address of the next executed instruction .
(2) Virtual machine stack (JVM Stack): Focus on storage Local variable table ( Of course, there are other information ). We just created int[] arr The reference of such storage address is saved here
(3) Local method stack (Native Method Stack): The function of local method stack is similar to that of virtual machine stack . Only the content saved is Native method( These functions implemented in C + + and called by Java )Local variable of In some versions JVM In implementation ( for example HotSpot), The local method stack and the virtual machine stack are together .
JVM is a program based on C + + In the process of Java program execution, it is also necessary to call some functions provided by C + + to interact with the bottom of the operating system Therefore, some functions implemented in C + + will also be called in java development
(4) Pile (Heap): JVM Maximum memory area managed . use new All objects created are saved on the heap ( For example, the previous new int[]{1, 2, 3} ) 
(5) Method area (Method Area): It is used to store class information, constants, static variables, code compiled by real-time compiler and other data that have been loaded by virtual machine Method is stored in this area .
(6) Runtime constant pool (Runtime Constant Pool): Is part of the method area , Storage literal quantity ( string constant ) And symbol reference . ( be careful from JDK 1.7 start , Runtime constant pool on heap )

2. One question:

Run the following code. What does it output?
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

null stay Java Medium representation " "Null reference", that is, an invalid reference, No read or write operations can be performed on this memory do There is no agreement in Java that null has any association with the memory of address 0.
For example: int[] arr = null// This means that arr does not point to any object, if we use system out. println(arr[0]); The compiler will report one Null pointerexception (null pointer) error
Note: NULL pointer of C language is uppercase, while java is lowercase

 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; 
    } 
}
In this way, the original array will not be destroyed In addition, because the array is a reference type, When returning, only the first address of the array is returned to the function caller , The contents of the array were not copied , So as to be more efficient

3, Some exercises of array

1. Array to string

(1) First, let's get to know the "package":

Program development is not from scratch, but to stand on the shoulders of giants For example, in the process of writing many programs, we don't have to implement all the details by ourselves. There are already a large number of standard libraries (code provided by JDK) and a large number of third-party libraries (code provided by other organizations) for us to use directly These codes are put in "packages" one by one. There are thousands of "packages" we can use
(2) Java Provided in java.util.Arrays package , It contains some common methods of manipulating arrays
toString(int[] a): output the integer array of parameters as a string, and the return value is static String
toString(float[] a): output the floating-point array of parameters in the form of string, and the return value is static String
...... Arrays of other data types, and so on
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

data type [][] Array name = new data type [ Number of rows ][ Number of columns ] { Initialization data };
2. Traversal of two-dimensional array. (a two-dimensional array is essentially a one-dimensional array)
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();
     }
}

Topics: Java JavaSE