A must-read for getting started with JavaSE - Detailed explanation of arrays

The concept of array

Suppose we now want to save the javaSE exam scores of 5 students and output them. We might do the following:

public class TestStudent{
    
    
  public static void main(String[] args){
    
    
    int score1 = 70;
    int score2 = 80;
    int score3 = 85;
    int score4 = 60;
    int score5 = 90;
    
    System.out.println(score1);
    System.out.println(score2);
    System.out.println(score3);
    System.out.println(score4);
    System.out.println(score5);
  }
}

We successfully achieved it, but what about 50? What about 500? What about 5,000? We can't define so many variables in sequence. Besides, they are all variables of the same data type . So what does java use to facilitate our use? This is the array that this article is about.

1. What is an array?

Array: can be thought of as a collection of elements of the same type. It is a continuous space in memory.

For example, in a garage: 1. Each parking space is used for parking; 2. The parking spaces are connected together; 3. The parking spaces have their own numbers.

  1. The elements stored in the array have the same type
  2. The spaces of the array are connected together
  3. Each space has its own number. In fact, the position number is 0, which is the subscript of the array.

2. How to create an array

Two common ways to initialize arrays:

  • 1. Dynamic initialization (specified length)
  • 2. Static initialization (specified content)

The specific syntax is as follows:

1. Dynamic initialization

Data type stored in the array [ ] Array name = new Data type stored in the array [array length];
Data type stored in the array Array name [ ] = new Data type stored in the array [array length]; // Not recommended

Examples of the first enumeration method are as follows:

int[] array1 = new int[10]; // 创建一个可以容纳10个int类型元素的数组
double[] array2 = new double[5]; // 创建一个可以容纳5个double类型元素的数组
String[] array3 = new double[3]; // 创建一个可以容纳3个字符串元素的数组

Note: 1.new:关键字,创建数组使用的关键字; 2.数组有定长特性,长度一旦指定,不可更改。
When we define the length without a specific value , our java will provide default value assignment:
Insert image description here

2. Static initialization

Data type [] array name = new data type [] {element 1, element 2, element 3...};

Examples are as follows:

int[] array1 = new int[]{
    
    0,1,2,3,4,5,6,7,8,9};
double[] array2 = new double[]{
    
    1.0, 2.0, 3.0, 4.0, 5.0};
String[] array3 = new String[]{
    
    "hell", "Java", "!!!"};
**3.Static initialization omit mode**

Our most commonly used method is to omit static initialization:

Data type [] array name = {1, element 2, element 3...};

Examples are as follows:

// 注意:虽然省去了new T[], 但是编译器编译代码时还是会还原
int[] array1 = {
    
    0,1,2,3,4,5,6,7,8,9};
double[] array2 = {
    
    1.0, 2.0, 3.0, 4.0, 5.0};
String[] array3 = {
    
    "hell", "Java", "!!!"};

Note:该方法不可拆分定义

3. Traverse the array

An array is a continuous space in memory. The number of the space starts from 0 and increases in sequence. This number is called the subscript of the array. The array can access its elements at any position through the subscript. For example:

int[]array = new int[]{
    
    10, 20, 30, 40, 50};
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]);

array[0] = 100;// 也可以通过[]对数组中的元素进行修改
System.out.println(array[0]);

【Precautions】

  1. An array is a continuous memory space, so it supports random access, that is, quick access to elements at any position in the array through subscript access.
  2. The subscript starts from 0 and is between [0, N) and does not include N. N is the number of elements and cannot cross the boundary. Otherwise, a subscript out-of-bounds exception will be reported.

for example:

int[] array = {
    
    1, 2, 3};
System.out.println(array[3]); // 数组中只有3个元素,下标一次为:0 1 2,array[3]下标越界
// 执行结果
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 100
       at Test.main(Test.java:4)

Three ways to traverse an array

Loop printing:

int[]array = new int[]{
    
    10, 20, 30, 40, 50};
for(int i = 0; i < 5; i++){
    
    
   System.out.println(array[i]);
}

int[]array = new int[]{
    
    10, 20, 30, 40, 50};
for(int i = 0; i < array.length; i++){
    
           //数组名.length求数组长度
   System.out.println(array[i]);
}

** for-each traverses the array: **
int[] array = {
    
    1, 2, 3};
for (int x : array) {
    
    
    System.out.println(x);
}
**Convert to characters and print:** ![Insert picture description here](https://img-blog.csdnimg.cn/31653a61b0d646d48af45d152ad1dd26.png)
import java.util.Arrays;

public class text1 {
    
    
    public static void main(String[] args) {
    
    
        int[] array={
    
    1,2,3,4,5,6};
        System.out.println(Arrays.toString(array));
    }
}

The effect is shown as follows:
Insert image description here

4.Extension: fast batch initialization

Arrays.fillQuick initialization, filling an array.
Let’s look at the instructions in the jdk1.8 help manual:
Insert image description here
Example:

import java.util.Arrays;

public class HelloWorld {
    
    
    public static void main(String[] args) {
    
    
        int[] arr = new int[5];
        Arrays.fill(arr, 1);
        System.out.println(Arrays.toString(arr));  // [1, 1, 1, 1, 1]
    }
}

Array principle memory diagram

1. Memory overview

Memory is an important component in the computer, a temporary storage area, and is used to run programs. The program we write is stored in the hard disk. The program in the hard disk will not run. It must be placed in the memory to run. After the operation is completed, the memory will be cleared. To run a program, the Java virtual machine must allocate and manage memory space.
To sum it up simply, it is the following four points:

  1. The code needs to be loaded into memory when the program is running
  2. Intermediate data generated by program execution must be stored in memory
  3. Constants in the program should also be saved
  4. Some data may need to be stored for a long time, while some data will be destroyed when the method ends.

2. Memory division of Java virtual machine

In order to improve computing efficiency, the space is divided into different areas, because each area has a specific way of processing data and memory management.

  • JVM memory partitioning
    Insert image description here

  • Virtual machine stack (JVM Stack): Some information related to method calls. When each method is executed, a stack frame will be created first. The stack frame contains:
    local variable table, operand stack, dynamic link, return address and Some other information is saved related to the execution of the method
    . For example: local variables. When the method ends, the stack frame is destroyed, that is, the data stored in the stack frame is also destroyed.

  • Heap: The largest memory area managed by the JVM. Objects created using new are all stored on the heap (such as the previous new int[]{1, 2, 3}). The heap is created when the program starts running
    . , it will be destroyed as the program exits. The data in the heap will not be destroyed as long as it is still in use
    .

3. Its storage method diagram

Reference variables do not directly store the object itself. It can be simply understood as storing the starting address of the object in the heap space.

Through this address, the object can be manipulated by referencing the variable. It is somewhat similar to pointers in C language, but references in Java are simpler to operate than pointers.

Insert image description here
Note:变量array保存的是数组内存中的地址,而不是一个具体数值,因此称为引用数据类型。

import java.util.Arrays;

public class text1 {
    
    
    public static void main(String[] args) {
    
    
        int[] array1={
    
    1,2,3,4,5,6};
        int[] array2=new int[6];
        array2=array1;
        System.out.println(Arrays.toString(array2));
        array2[1]=300;
        System.out.println(Arrays.toString(array1));
    }
}

Insert image description here
Please think about why there is such an effect. You can send a private message to the blogger!

4. Get to know null

Null means "null reference" in Java, that is, a reference that does not point to an object. The role of null is similar to NULL (null pointer) in C language, both of which represent an invalid memory location. Therefore, no operations can be performed on this memory. Read and write operations.

int[] arr = null;
System.out.println(arr[0]);
// 执行结果
Exception in thread "main" java.lang.NullPointerException
at Test.main(Test.java:6)

Two-dimensional array

Two-dimensional array initialization

Just like arrays of the same dimension, there are 4 different definition methods:

int[][] array1 = new int[10][10];
int array2[][] = new int[10][10];
int array3[][] = {
    
     {
    
     1, 1, 1 }, {
    
     2, 2, 2 } };
int array4[][] = new int[][] {
    
     {
    
     1, 1, 1 }, {
    
     2, 2, 2 } };

Note:二维数组定义不可省略行

Irregular two-dimensional array:

int[][] array = new int[3][];
array[0] = new int[1];
array[1] = new int[2];
array[2] = new int[3];

Traverse a two-dimensional array

import java.util.Arrays;

public class text1 {
    
    
    public static void main(String[] args) {
    
    
        int[][] array={
    
    {
    
    1,2,3},{
    
    2,4,5},{
    
    1,2}};
        System.out.println(Arrays.deepToString(array));

    }
}

Insert image description here

Common array exceptions

1. Array out of bounds exception

public static void main(String[] args) {
int[] arr = {1,2,3};
System.out.println(arr[3])
}

The error message is as follows:

Insert image description here

The index of the array is 0.1.2, there is no 3 index, so we cannot access an index that does not exist in the array. This exception must be modified!

2. Array null pointer exception

we are atKnow nullAlready briefly explained in , let’s look at memory:
Insert image description here

Java Common API

1. Output arrayArrays.toString()

 int[] array = {
    
     1, 2, 3 };
 System.out.println(Arrays.toString(array));

2. Array copycopyOf()

import java.util.Arrays;

public class text1 {
    
    
    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(array));
        System.out.println(Arrays.toString(ret));

    }
}

The effect is as follows:
Insert image description here

3. Array sortingsort()

import java.util.Arrays;

public class text1 {
    
    
    public static void main(String[] args) {
    
    
        int[] array={
    
    1,6,5,4,9};
        System.out.println(Arrays.toString(array));
        Arrays.sort(array);
        System.out.println(Arrays.toString(array));

    }
}

Insert image description here

4. Convert two-dimensional array to character printingdeepToString()

import java.util.Arrays;

public class text1 {
    
    
    public static void main(String[] args) {
    
    
        int[][] array={
    
    {
    
    1,2,3},{
    
    2,4,5},{
    
    1,2}};
        System.out.println(Arrays.deepToString(array));

    }
}

Using arrays and methods

In java, arrays can be used as return values

Example: Fibonacci Sequence->

public class text1 {
    
    
    public static int[] fib(int n){
    
    
        if(n <= 0){
    
    
            return null;
        }
        int[] array = new int[n];
        array[0] = array[1] = 1;
        for(int i = 2; i < n; ++i){
    
    
            array[i] = array[i-1] + array[i-2];
        }
        return array;
    }
    public static void main(String[] args) {
    
    
        int[] array = fib(10);
        for (int i = 0; i < array.length; i++) {
    
    
            System.out.println(array[i]);
        }
    }
}

Some screenshots are as follows:
Insert image description here

Guess you like

Origin blog.csdn.net/m0_65038072/article/details/127719874