Definition and use of Java array

Keywords: Java Back-end

catalogue

1 basic usage of array

1.1 what is an array

1.2 creating arrays

  1.3 use of arrays

  2 array as parameter of method

2.1 basic usage

2.2 understanding of references

  2.3 understanding

2.4 understand JVM memory area division

3 array as the return value of the method

  4 array exercises

4.1 array to string

4.2 find the specified element in the array (binary search)

1 basic usage of array

1.1 what is an array

An array uses a continuous space to store some data of the same type.

Each data in the array has its own unique index, which is also the identification of accessing the element. Subscripts start at 0

For example, there are five numbers in the array, and the data in it corresponds to the sub subscript of the data, as shown in the figure

 

For example:

1, 2, 3, 4, 5, 6 and 7 can be stored in an array

1.2 creating arrays

Basic syntax:

Data type [] array name = {initialization data};

Data type [] array name = new data type [number of data to be stored] {initialization data};

Example code:

int[]array1={1,2,3,4,5};
int[]array2=new int[5]={1,2,3,4,5};

  1.3 use of arrays

There are two basic uses of arrays: 1 is the length of the array or de array, and 2 is to access each element of the array

Example code:

 public static void main(String[] args) {
        int[]array={1,2,3,4,5};
        //Gets the length of the array
        int len=array.length;
        System.out.println(len);
        //Access the array through the index of the array
        System.out.println(array[0]);
    }

  matters needing attention

1. use arr.length The length of the array can be obtained . . This operation is a member access operator . Later, it will be often used in object-oriented .
2. use [ ] Press to mark array elements . Need attention , Subscript from 0 Start counting
3. use [ ] The operation can read data , Data can also be modified .
4. The subscript access operation cannot exceed the valid range [0, length - 1] , If out of valid range , A subscript out of bounds exception occurs
Array use example code: array traversal
public static void main(String[] args) {
        int[]array={1,2,3,4,5};
        //for loop traversal
     for(int i=0;i<array.length;i++){
         System.out.print(array[i]+" ");
     }
        System.out.println();
     //foreach traverses the array,
        for (int x:
             array) {
            System.out.print(x);
        }
        System.out.println();
    }

  2 array as parameter of method

2.1 basic usage

Example code: traversal of array

 public static void playArray(int[]array){
        for (int i = 0; i <array.length ; i++) {
            System.out.print(array[i]+" ");
        }
        System.out.println();
    }
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        playArray(arr);

    }

  In this code, arr is an argument, array is a formal parameter, and array.length can also obtain the length of the array

2.2 understanding of references

First, let's look at the following code:

 public static void change(int num){
        num=20;
        System.out.println("num="+num);
    }
    public static void main(String[] args) {
        int a=10;
        change(a);
        System.out.println("a="+a);
    }

Obviously, we can't change a through methods, because num is just a copy of A. they just have the same value

So what should we do if we want to modify a spatial data through a method?

The concept of reference is introduced here

Reference: reference is also a variable, but it stores the address of an object (the concept of object will be discussed later).

Let's look at a piece of code

 public static void change(int[]array){
        for(int i=0;i<array.length;i++){
            array[i]*=2;
        }
    }
    public static void main(String[] args) {
       int arr[]={1,2,3,4,5};
       change(arr);
       playArray(arr);
    }

 

We can see that the data in the array has been changed. Why is this? Let's discuss this problem below.

First of all, I want to tell you that an array is a reference type. The array name is the variable name of the reference type, and the address of the elements in the array is stored in the variable. Then, a copy of array to arr, that is, the same address is also stored in array. Through the address, the value of the space corresponding to the address can be changed.

As shown in the figure:

  2.3 understanding

null stay Java Medium representation " Null reference " , That is, an invalid reference .
null The effect is similar to C In language NULL ( Null pointer ), Indicates an invalid memory location . Therefore, no read and write operations can be performed on this memory
do . Once you try to read and write , Will throw NullPointerException.
Note: there is no agreement in Java that null has any association with memory with address 0

2.4 understand JVM memory area division

The inner dimension of the JVM is divided into several different regions

Program counter (PC Register): It's just a small space , Save the address of the next executed instruction .
VM 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
Native Method Stack (Native Method Stack): The local method stack is similar to the virtual machine stack . Only the content saved is Native Method In some versions JVM In implementation ( for example HotSpot), The local method stack and the virtual machine stack are together .
heap (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} )
Method area (Method Area): It is used to store class information, constants, static variables, code compiled by the real-time compiler, etc. that have been loaded by the virtual machine
according to . Method is stored in this area .
Runtime Constant Pool (Runtime Constant Pool): Is part of the method area , Storage literal quantity ( string constant ) And symbol references . ( be careful from JDK 1.7 start , Runtime constant pool (on heap)
Native method :
JVM Is based on C++ Implemented program . stay Java During program execution , Essentially, it also needs to be called C++ Some functions provided for and operation
Do some interaction at the bottom of the system . So in Java Some will also be called during development C++ Implemented functions .
there Native That's what the method means C++ Realized , Again by Java Function to call

3 array as the return value of the method

Example code: expand each element in an array by 2 times and return

public static  int[]toDouble(int[]array){
    int[]returnArray=new int[array.length];
        for (int i = 0; i <array.length ; i++) {
            returnArray[i]=array[i];
        }
        return returnArray;
    }   
public static void main(String[] args) {
       int arr[]={1,2,3,4,5};
       playArray(toDouble(arr));
    }

  4 array exercises

4.1 array to string

code:

 /**
     * Array to string
     * @param array Array to convert
     * @return Converted String
     */
    public static String toString(int[]array){
        String str="[";
        for(int i=0;i<array.length;i++){
            str+=array[i];
            if(i<array.length-1){
                str+=",";
            }
        }
        str+="]";
        return str;
    }
 public static void main(String[] args) {
       int arr[]={1,2,3,4,5};
        System.out.println(toString(arr));
    }

4.2 find the specified element in the array (binary search)

in the light of Ordered array , You can use more efficient binary lookups .
What is an ordered array ?
Orderly divided into " Ascending order " and " Descending order "
as 1 2 3 4 , Ascending order is ascending order .
as 4 3 2 1 , Descending order is descending order .
Take an ascending array as an example , The idea of binary search is to take the element in the middle first , See if the value you are looking for is larger or smaller than the middle element . If small , Just go to the left ; Or go to the right
code:
 /**
     * Binary search
     * @param array Array to find
     * @param key Number of to find
     * @return If it is found, it returns the subscript of the number to be found. If it is not found, it returns an error message
     */ 
public static int binarySearch(int[]array,int key){
        int left=0;
        int right=array.length-1;
        while(left<=right){
            int mid=(left+right)/2;
            if(array[mid]>key){
                right=mid-1;
            }else if(array[mid]<key){
                left=mid+1;
            }else{
                return mid;
            }
        }
        return -1;
    }
 public static void main(String[] args) {
       int arr[]={1,2,3,4,5};
        System.out.println(binarySearch(arr,2));
    }

 

 

Posted by colby.anderson on Sun, 24 Oct 2021 06:07:37 -0700