I learn Java in VScode (Java one-dimensional array, two-dimensional array, heap and stack in JVM) remake

My personal blog homepage: If '' can really escape 1️⃣ say 1️⃣ blog homepage
about Java basic grammar learning ----> you can refer to my blog: "I learn Java in VScode"

Java one-dimensional array, two-dimensional array

zero._.in java_what is an array

1.>A Java array is a data structure that stores a set of data of the same type.

(1) Both Java and other high-level languages ​​provide a data structure that uses a unified array name and different subscripts to uniquely determine the elements in the array (array).
(2) An identifier can be used to encapsulate and store a basic type data sequence or object sequence with a fixed number of elements and the same element type. (is a simple linear sequence, so access is fast.)

[1] 数组在Java 中是一个对象,可以通过声明一个数组变量来创建。

[In Java, to declare an array variable, you need to specify the type and name of the array, and then use square brackets to specify the size of the array. 声明一个包含5个整数的数组 int[] myArray = new int[5];

[2] 数组变量包含一个指向数组对象的引用,而数组对象包含实际的数据。
数组变量和数组对象之间的关系:

When you create an array, you actually allocate a continuous space in memory to store data, and store the reference of the array variable pointing to this space in the variable. The following will describe how arrays are stored in Java.
数组是一种对象类型,因此可以使用new关键字来创建一个数组对象 int[] myArray = new int[5];

2> Reference data type 1 , default value, array length:

【1】Java数组是引用数据类型,长度属性为 length。
【2】Java数组下标是从零开始的,Java数组下标访问运算符[ ].
【3】数组元素的默认值:
    对于基本数据类型 0,0.0,‘\u000’
    对于引用元素数据类型string,object等为 null。
    对于Boolean类型,为false
【4】数组的长度:数组名.length。
	数组的元素是通过索引访问。索引从 0 开始,索引值从 0 到 array.length-1。

Defaults

int[] intArray = new int[5];
System.out.println(intArray[0]); // 输出0
double[] doubleArray = new double[5];
System.out.println(doubleArray[0]); // 输出0.0
char[] charArray = new char[5];
System.out.println(charArray[0]); // 输出空字符
boolean[] boolArray = new boolean[5];
System.out.println(boolArray[0]); // 输出false
String[] strArray = new String[5];
System.out.println(strArray[0]); // 输出null

3> store the same data type -> consider implicit conversion

Select different types of arrays according to different types to store multiple values ​​of the same data type.When storing data in an array, implicit conversion needs to be considered.
It is necessary to keep the type of the array container consistent with the stored data type

For example: array container of type int ( byte short int ) [disadvantages should be controlled]
For example: array container of double type double ( byte short int long float double )

One._.one-dimensional array

1> Explanation:

A one-dimensional array in Java is a data structure used to store elements of the same type. [Such as: storing basic data types (such as int, float, etc.) and object types (such as String, Object, etc.).
Each element can be accessed by its index, which starts at 0 and ends with the length of the array - 1 and ends at 2 .

2> Declaration and initialization

Understanding Java Array Declaration and Initialization.

创建数组:分配数据存储的物理空间是在堆上 arrayRefVar = new dataType[arraySize];

【1】Array Declaration_ Array declaration: Array variables must be declared before the array can be used normally in the program.

Declaring an array means creating an array variable, but not allocating memory space for it. For example: int[] myArray;
Here we declare an integer array named myArray, but it has not been initialized, that is to say, it has not been assigned a specific array object.

elementType[] arrayRefVar;   // 首选的方法
dataType arrayRefVar[];  // 效果相同,但不是首选方法

double [] douarray;
int inarr[];

In the Java language, the form of [data type [] array name] is used, while [data type array name []] retains the form of C/C++. Nowadays, more and more language styles adopt the first form.

【2】Array Initialization_Initialize the array (start allocating space) —> There are three methods: static initialization, dynamic initialization and default initialization.

Initializing an array refers to allocating memory space for the array and assigning an initial value to it. For example: int[] myArray = new int[]{1, 2, 3};
The initialization of a Java array tells the compiler the size of the array and the values ​​of the elements. Here we initialize an integer array named myArray, which is assigned as an array object containing three elements, and the values ​​of these three elements are 1, 2, and 3 respectively.
Arrays can be initialized at declaration time or later in the code.

(1) Static initialization —> is performed at compile time.

Static initialization of a Java array refers to allocating space for the array and initializing its elements when declaring it. This can be done by using curly braces when declaring the array,int[] myArray = new int[]{1, 2, 3};

完整格式: 数据类型 [] 数组名 = new 数据类型[]{
    
    元素1,元素2....};
简化格式: 数据类型 [] 数组名 =[ 元素1,元素2,元素3...};
//根据不同类型选择不同类型的数组
范例: int[] array=112233);
范例: double []array2 ={
    
     11.122.233.3);

Get the address value and hash code ----> the address value is in hexadecimal, and its conversion to decimal is our hash code

地址值是对象在内存中的实际物理地址,是在内存中的位置可以通过Java中的System.identityHashCode(Object obj)方法获取。
	地址值的主要作用是在底层实现中进行对象的访问和操作。

哈希码是根据对象的内容计算出来的一个int类型的值,根据对象的内容计算出来的一个整数值。
	可以通过Java中的Object.hashCode()方法获取。哈希码的主要作用是在集合类中进行对象的查找和比较,例如HashMap、HashSet等。使用了一个常见的哈希码实现,称为"乘法散列”。
	
需要注意的是,哈希码并不是唯一的,不同的对象可能会有相同的哈希码。
	而地址值是唯一的,每个对象在内存中都有一个唯一的地址。
 int[] arr = {
    
     1, 2, 3 };
 int address = System.identityHashCode(arr);
 System.out.println("The address of the array is: " + address);
 System.out.println("The address of the array is: " + arr);

Line 3 outputs the address of the array in memory, and line 4 outputs the elements stored in the array. If you want to get the address of the array in memory, you need to use the System.identityHashCode() method.
insert image description here

//扩展:
[D@776ec8df
//解释一下地址值的格式含义
//[ : 表示当前是一个数组
//D: 表示当前数组里面的元素都是double类型的
//@: 表示一个间隔符号。 (固定格式),@是没有含义的
//776ec8df: 才是数组真正的地址值, (十六进制)
//平时我们习惯性的会把这个整体叫做数组的地址值

The hexadecimal conversion of the address value to decimal is our hash codeinsert image description here

You can use the identityHashCode method in Java's built-in System class. This method returns an object's hash code, which can be used to represent the object's address value. In your code, you can use the following code to get the address value of the myArray array: System.out.println(System.identityHashCode(myArray));
This address value is a hash code, not a real memory address. Therefore, it cannot be used to do pointer arithmetic or other low-level operations.

What is a hash code:

In Java, each object has a default hash code, which can be obtained using the hashCode() method. By default, the hashCode() method returns the entire representation of the object's memory location. However, it can be changed by enclosing hashode() method to provide a custom hashcode implementation. This custom hash code should be calculated based on the object's content, not the object's memory location. This ensures that objects with the same content have the same hash code, improving hash table performance. The following is a simple Java class that demonstrates how to override the hashCode() method to provide a custom hashcode implementation:

Hash Code (Hash Code) refers to compressing a message of any length into a fixed-length message digest, usually a fixed-length byte sequence. Hash codes are generated by an algorithm called a hash function, which maps an arbitrary-length message to a fixed-length message digest. The characteristic of the hash code is uniqueness, that is, different messages will generate different hash codes, and the hash codes generated by the same message are also the same. Hash codes are often used in data encryption, data compression, data integrity verification and other fields.

use
System.out.println("The address of the array is: " + address);//681842940
System.out.println("The address of the array is: " + System.identityHashCode(arr[0]));//1392838282
System.out.println("The address of the array is: " + System.identityHashCode(arr[1]));// 523429237
System.out.println("The address of the array is: " + System.identityHashCode(arr[2]));//664740647
why not continuous

This is because Java arrays are not necessarily stored contiguously in memory. Java arrays are objects, how they are stored in memoryDepends on the Java Virtual Machinerealization. In some cases, the Java virtual machine may store arrays in a contiguous block of memory, but in other cases they may be scattered and stored in different locations in memory. Therefore, you cannot assume that Java arrays are stored contiguously in memory.

Notice

In Java, only objects and arrays have address values. Primitive types (such as int, boolean, etc.) do not have address values.

 Scanner sc = new Scanner(System.in);

        int c = sc.nextInt();

        System.out.println(Integer.toHexString(System.identityHashCode(c)));
        System.out.println(System.identityHashCode(c));

        sc.close();
12
2d98a335
764977973
Since the integer has no address value, why is the address value still generated:

This is because all types in Java are objects, including primitive types. In Java, primitive types are encapsulated in objects and these objects are called wrapper classes. For example, the integer type int is encapsulated in the Integer class. Therefore, even if your variable is an integer type, it is still an object, so you can use the System.identityHashCode() method to get its address value.

where to store

According to Java's memory model, objects and arrays are allocated in heap memory, while primitive types and reference variables are allocated in stack memory. Therefore, an address value in Java is a reference to an object or an array in heap memory, so the address value is in heap memory.

Precautions

In Java, a stack is a data structure used to store method calls and local variables. The address value of the stack refers to the pointer to the top of the stack. Whenever a method is called, a new stack frame is created and pushed onto the stack. When the method returns, the stack frame is popped off the stack. Therefore, the stack address value changes as method calls are pushed and popped.

On the other hand, the heap is an area used for dynamically allocating memory. In Java, all objects are stored on the heap. Objects in the heap can be accessed by reference instead of directly accessing the heap address value.

Therefore, the stack address value and the heap address value are different concepts, and their functions and uses are also different. Stack address values ​​are used to track method calls and local variables, while heap address values ​​are used to track dynamically allocated objects.

(2) Dynamic initialization —> performed at runtime.

Dynamic initialization: only the length of the array is specified during initialization, and the system assigns the initial value to the array. Format :数据类型[]数组名 = new 数据类型数组长度[];
When creating, we specify the length of the array by ourselves, and the default initialization value is given by the virtual machine

In Java, dynamic initialization of an array means that when declaring the array, only the length of the array is specified, and the value of the array elements is not specified. For example, int[] myArray = new int[5];in this code, we declare that the scenario of dynamically initializing an array includes:
an integer array named myArray, and specify its length as 5. Since we did not specify the value of the array element, Java will automatically initialize all elements to the default value 0.

When you need an array with a fixed size, but you don't know the values ​​of the array elements. When you need an array with a fixed size, and you know the values ​​of the array elements, but these values ​​cannot be determined at runtime In the
second case, you can use static initialization of the array to specify the values ​​of the array elements. For example:
int[] myArray = {1, 2,3,4,5};In this code, we declare an integer array called myArray and specify the values ​​of its elements as 1, 2, 3, 4 and 5.

illustrate

dataType[] arrayName = new dataType[arraySize];
Note that when an array is initialized dynamically, the elements in the array are automatically initialized to their default values. For example, for an integer array, all elements will be initialized to 0. If you want to set the elements in the array to different values, you can use a loop or assign the values ​​one by one.
When using the new keyword to dynamically initialize an array, a memory space will be allocated in the heap to store the array elements. If you initialize an array with the new keyword multiple times, multiple memory spaces are allocated in the heap, each containing its own data.

(3) Default initialization

The value of a default-initialized array depends on the type of the array. If the array is of a primitive type (like int, double, etc.), the default value is 0. If the array is of object type, the default value is null.

[3] The difference between static initialization and dynamic initialization

(1) Number and given value

	动态初始化是在运行时进行的和元素的值都可以在运行时确定,
而在静态初始化中,数组的大小和元素的值都在编译时确定。

Static initialization: Manually specify the array elements, and the system will calculate the length of the array based on the number of elements. The specific data to be operated has been specified in the requirements, and the static initialization can be done directly.int[] arr = (11, 22, 33);

Dynamic initialization: Manually specify the length of the array, and the default initialization value is given by the system.Only the number of elements is specified, but the specific value is not specified, it is recommended to use dynamic initializationint[] arr = new int[5];

只要在定义数组时就已经确定了数组的元素个数和元素值,就是静态初始化。
	而动态初始化只确定了数组的长度,而数组的元素值需要在后续的代码中进行赋值.
静态初始化时就已经确定了,不需要在new后面的数提类型的[]里面写。
	因为在静态初始化时,编译器会根据你提供的元素个数自动计算出数组的长度,因此你只需要在[]里面提供元素即可。

(2) Another difference is that dynamic initialization can change the size of the array at runtime, while static initialization cannot.

总的来说,动态初始化和静态初始化都是初始化Java数组的有效方法。它们的主要区别在于初始化时间和数组大小是否可以更改
如果您需要向数组添加后续元素则应该使用动态初始化
如果您使用静态初始化创建Java数组,则无法向数组添加后续元素,因为数组的大小已经在编译时确定

What is required to dynamically add subsequent elements If you create a Java array using dynamic initialization, you can use the following code to add subsequent elements to the array:


int[] dynamicArray = new int[5];
dynamicArray[0] = 1;
dynamicArray[1] = 2;
dynamicArray[2] = 3
dynamicArray[3] = 4
dynamicArray[4] = 5;
dynamicArray = Arrays.copyof(dynamicArray,10)
dynamicArray[5] = 6;
dynamicArray[6] = 7;
dynamicArray[7] = 8;
dynamicArray[8] = 9;
dynamicArray[9] = 1;
在上面的代码中,我们首先使用动态初始化创建了一个名为dnamicArray 的整数数组,并将其初始化为长度为5的数组,然后,我们使用索引将12345添加到数组中。
下来,我们使用Arrays.copy()方法将数组的大小更改为10。最后,我们使用索引将678910添加到数组中。
请注意,如果您使用静态初始化创建Java数组,则无法向数组添加后续元素,因为数组的大小已经在编译时确定。如果您需要向数组添加后续元素,则应该使用动态初始化

Create a Java array using static initialization, you cannot add subsequent elements to the array because the size of the array is already atDetermined at compile time.静态初始化是在创建数组时同时指定数组大小和元素的过程

The size of the array created by static initialization is fixed, so it is not possible to add subsequent elements to the array.
(1) If you need to add subsequent elements to the array, you should use dynamic initialization.
(2) You can change the value of size as needed to dynamically adjust the size of the array at runtime.

数据类型[] 数组名= new 数据类型[]{元素1,元素2....}; , called static initialization.
Contention state initialization method. This method has already determined the number of elements and element values ​​of the array when defining the array, so it is also
数据类型[] 数组名 = new 数据类型[数组长度]called dynamically initialized array
. Among them, the length of the array can be an integer or a variable. This method only determines the length of the group when defining the array, and the element values ​​of the array need to be assigned in subsequent codes.

3> Dynamically allocate memory

Java also provides other methods, such as ArrayList and LinkedList. These classes allow you to add and remove elements at runtime without manually managing memory allocation.

//java.util.Scanner类从用户读取输入。Scanner类允许您从标准输入读取用户输入。
import java.util.ArrayList;

public class MyClass {
    
    
    public static void main(String[] args) {
    
    
        ArrayList<Integer> intList = new ArrayList<Integer>();
        intList.add(1);
        intList.add(2);
        intList.add(3);
        System.out.println(intList); // 输出 [1, 2, 3]
    }
}

4> Process the array content

Generally use the basic three loops or For-Each loop.

For-Each loop, or enhanced loop, which traverses an array without subscripting.

int[] intArray = {
    
    1, 2, 3, 4, 5};

// 使用for-each循环输出数组元素
for (int i : intArray) {
    
    
    System.out.println(i);
}

Do not specify the length of the array and assign an initial value to each array element when initializing the array, as this will cause code errors.

Out-of-bounds access array—>Warning
Warning Out-of-bounds access to an array is a programming error that often occurs, and it will throw a running error. ArrayIndexOut0fBoundsException。In order to avoid errors, you should ensure that the subscript used does not exceedarrayRefVar.length-1。

The main reason: it is a mistake that will be made when <= is misused in the place where < should be used in the loop.


5> Method:

Binary search:

For left-closed right-closed intervals:

public class BinarySearch {
    
    

public static int binarySearch(int[] arr, int target) {
    
    
    int left = 0;
    int right = arr.length - 1;

    while (left <= right) {
    
    
        int mid = left + (right - left) / 2;

        if (arr[mid] == target) {
    
    
            return mid;
        } else if (arr[mid] < target) {
    
    
            left = mid + 1;
        } else {
    
    
            right = mid - 1;
        }
    }

    return -1;
}

For left-closed right-open intervals:

public class BinarySearch {
    
    
    public static int binarySearch(int[] arr, int target) {
    
    
        int left = 0;
        int right = arr.length;

        while (left < right) {
    
    
            int mid = left + (right - left) / 2;

            if (arr[mid] == target) {
    
    
                return mid;
            } else if (arr[mid] < target) {
    
    
                left = mid + 1;
            } else {
    
    
                right = mid;
            }
        }

        return -1;
    }

to sort

insert image description here

​Built-in
method:
array with length 0 is not null

(1)Arrays.sort():该方法使用快速排序算法对数组进行排序。时间复杂度为O(nlogn)。
int[] arr = {
    
    3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5};
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));
(2)Collections.sort():该方法使用归并排序算法对列表进行排序。时间复杂度为O(nlogn)
List<Integer> list = new ArrayList<>(Arrays.asList(3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5));
Collections.sort(list);
System.out.println(list);

6> Some terminology:

anonymous array (anonymous array)
array initializer (array initialization syntax)
binary search (binary search)
index (subscript)
indexed variable (subscript variable)
insertion sort (insertion sort)
linear search (linear search)
selection sort (selection sort
)

7> Summarize according to the content of learning and books:

  • Declaring an array variable does not allocate any space for the array. Array variables are not primitive data type variables. Array variables contain references to arrays. When creating an array, if its elements are values ​​of the basic data type, then the default value of the initial value of the array is consistent with the changed data type.

  • Values ​​can only be assigned to array elements after the array has been created. Arrays can be created using the new operator, the syntax is as follows: newelementType[array.Size] (data type[array size]).

  • Each element in an array is represented using the syntax arravRefVarlindex1(array reference variable[subscript]). Subscript must be an integer or an integer expression.

  • After the array is created, its size cannot be changed, use array.length to get the size of the array. Since array subscripts always start from 0, the last subscript is always array.length-1. An out-of-bounds error occurs if an attempt is made to reference an element outside the bounds of the array. Never access the first element of an array with subscript 1, which should actually be 0 for that element. This error is called an index off-by-one error.

  • Java has an expression called array initializer, which combines the declaration, creation, and initialization of arrays into one statement, whose syntax is:元素类型[] 数组引用变量={value0,value1,.·,valuek}

  • When you pass an array parameter to a method, you are actually passing a reference to the array, or more precisely, the called method can modify the elements of the caller's original array.

2._. Two-dimensional array

The advantage of Java using big-endian is that it allows for easier interoperability between different systems. This is because big-endian is the most widely used byte order in network protocols and file formats. [To communicate and exchange data. ]

二维数组是Java中的一种数据结构,它可以被看作是一个由多个一维数组组成的数组。
每个一维数组都代表着一个行,而这些一维数组的长度可以不同。 [用于存储表格数据,例如矩阵、棋盘等等。]

1> Java two-dimensional array creation

To create a two-dimensional array in Java, you can use the following syntax:

//Length1 和 Length2 是整数 【左行右列】
type[][] typeName = new type[Length1][Length2];

//拥有以下3种格式
type[][] arrayName = new type[][]{
    
    1,2,3,,值 n};    // 在定义时初始化
type[][] arrayName = new type[Length1][Length2];    // 给定空间,在赋值
type[][] arrayName = new type[Length1][];    // 数组第二维长度为空,可变化

create form

int[][] arrayName = new int[rows][columns];
//创建一个具有3行和4列的二维数组
int[][] arrayName = new int[3][4];

数组名 = new 数据类型[1维的长度][];

//单独初始化每一行来创建二维数组
int[][] arrayName = new int[3][];
arrayName[0] = new int[4];
arrayName[1] = new int[5];
arrayName[2] = new int[6];

To initialize a two-dimensional array, you create an array with the desired number of rows and then allocate space for each row by assigning to each row a new array with the desired number of columns.

Dynamic initialization of multidimensional arrays (take two-dimensional arrays as an example)

Directly allocate space for each dimension, the format is as follows: type can be basic data type or compound data type, typeLength1 and typeLength2 must be positive integers, typeLength1 is the number of rows, and typeLength2 is the number of columns.

int[][] a = new int[2][3];

The two-dimensional array a can be regarded as an array with two rows and three columns.

  1. Allocate space for each dimension separately, starting with the highest dimension, for example:
String[][] s = new String[2][];
s[0] = new String[2];
s[1] = new String[3];
s[0][0] = new String("Good");
s[0][1] = new String("Luck");
s[1][0] = new String("to");
s[1][1] = new String("you");
s[1][2] = new String("!");

type[][] typeName = new type[typeLength1][typeLength2];

2>Java Array --> allocate space for each dimension

​​insert image description here

Example of array initialization starting from higher dimensions:

a = new int[3][]; // 先为第一维分配空间,注意这时没有为第二维分配空间 
a[0] = new int[2]; // 然后为第二维的每一个元素(数组)分配空间 
a[1] = new int[1]; 
a[2] = new int[3];

Java Two-dimensional Array Realization Algorithm

For matrix operations, store the values ​​of the matrix and perform operations such as addition, subtraction, and multiplication.

For image processing, represent the pixels of an image and apply filters or transformations to the image.

For graph algorithms, represent the adjacency matrix of a graph and perform operations such as finding the shortest path between two nodes

Matrix operation –> multiplication

int[][] matrix1 = {
    
    {
    
    1, 2, 3, 4, 5}, {
    
    6, 7, 8, 9, 10}};
int[][] matrix2 = {
    
    {
    
    1, 2}, {
    
    3, 4}, {
    
    5, 6}, {
    
    7, 8}, {
    
    9, 10}};
int[][] result = new int[2][2];

for (int i = 0; i < 2; i++) {
    
    
    for (int j = 0; j < 2; j++) {
    
    
        for (int k = 0; k < 5; k++) {
    
    
            result[i][j] += matrix1[i][k] * matrix2[k][j];
        }
    }
}

// 打印结果
for (int i = 0; i < 2; i++) {
    
    
    for (int j = 0; j < 2; j++) {
    
    
        System.out.print(result[i][j] + " ");
    }
    System.out.println();
}

Ninety-nine multiplication table:

for (int i = 0; i < 9; i++) {
    
    
    for (int j = 0; j < 9; j++) {
    
    
        table[i][j] = (i + 1) * (j + 1);
    }
}
for (int i = 0; i < 9; i++) {
    
    
    for (int j = i; j < 9; j++) {
    
    
        System.out.print((i+1) + "*" + (j+1) + "=" + table[i][j] + "\t");
    }
    System.out.println();
}

3._. Irregular array

In Java, an irregular array is also called an "irregular multi-dimensional array" or "staggered array", which refers to an array structure in which nested one-dimensional arrays have inconsistent lengths.
The way of declaring an irregular array is similar to declaring an ordinary multi-dimensional array, except that the length of each one-dimensional array needs to be specified when declaring. For example, to declare a two-dimensional ragged array:

int[][] arr = new int[3][];
arr[0] = new int[]{1, 2, 3};
arr[1] = new int[]{4, 5};
arr[2] = new int[]{6, 7, 8, 9};

The above code creates a two-dimensional irregular array arr, in which the length of the first dimension is 3, and the length of the second dimension is inconsistent. The first one-dimensional array contains 3 elements, the second one-dimensional array contains two elements, and the third one-dimensional array contains four elements.
We can also create a ragged array as follows:

int[][] arr = {
   
   {1, 2, 3}, {4, 5}, {6, 7, 8, 9}};

Using loop statements to access irregular arrays can use nested loops with different dimensions, for example:

for (int i = 0; i < arr.length; i++) {
    for (int j = 0; j < arr[i].length; j++) {
        System.out.print(arr[i][j] + " ");
    }
    System.out.println();
}

The above code will output the following result:

1 2 3 
4 5 
6 7 8 9 

Precautions

When using irregular arrays, you need to pay attention to the following points:

  1. The length of each one-dimensional array in the irregular array can be different, but each one-dimensional array itself must be a legal array object, otherwise a NullPointerException will be thrown.
  2. When creating an irregular array, you must first create the first-dimensional array, and then allocate memory space for each one-dimensional array in turn.
  3. When accessing the elements of a ragged array, nested loop statements are required. Since the length of each one-dimensional array is different, you need to use arr[i].length to get the length of the i-th one-dimensional array.
  4. The length of the irregular array is immutable, once created, the size of the array cannot be changed. If you need to add or delete elements, you need to create a new array and copy the elements in the old array to the new array.
  5. The performance of irregular arrays may be worse than regular arrays, because irregular arrays need to be implemented using multiple one-dimensional arrays, and because each one-dimensional array has a different length, it may cause memory fragmentation problems. Therefore, in practical applications, an appropriate data structure should be selected to store data according to the specific situation.

4._.Other knowledge points

Stack----the memory used when the method is running, such as the main method running, enter the method stack to execute
Heap----store objects or arrays, created by new, all stored in the heap memory
method area----storage can Running class file
Local method stack - used by JVM when using operating system functions, which has nothing to do with our development
Register - used by CPU, has nothing to do with our development

1> stack

The memory used when the method is running, such as the main method running, enters the method stack for execution. 开始执行时会进栈代码执行完毕会出栈.The access speed is faster than the heap, the data size and lifetime in the stack must be determined, and the stack data can be shared.
The memory of the stack is much smaller than the memory of the heap, so recursion is less used

Stack: It is mainly used to store local variables and reference variables of objects. Each thread will have an independent stack space, so data is not shared between threads.

Java does allocate memory space for variables on the stack. When a variable goes out of scope, Java automatically releases the memory space allocated for the variable so that the space can be used for other purposes immediately. The stack memory belongs to a single thread, and each thread has a stack memory, and the variables stored in it can only be seen in the thread to which it belongs, that is, the stack memory can be understood as the private memory of the thread. However, the situation is different for objects allocated in heap memory. Objects in heap memory are visible to all threads because they do not belong to any particular thread.

2> heap

new to create, are stored in the heap memorynew 出来的东西会在这块内存中开辟空间并产生地址

Heap: Mainly used to store instantiated objects and arrays. The memory space is dynamically allocated by the JVM [variables of basic types and reference variables of objects are allocated in the stack memory of the function. 】. A JVM has only one heap memory, and threads can share data.

Objects in heap memory are visible to all threads. This means objects in heap memory can be accessed by all threads. This is an important aspect of multithreaded programming in Java as it allows multiple threads to access and manipulate the same object concurrently.

1. As long as it is new, it must open up a small space in the heap.
2. If new is created multiple times, there are multiple small spaces in the heap, and each small space has its own data.

3> Understand again through CursorCode

insert image description here

4> When two arrays point to the same small space, one of the arrays changes the value in the small space, then when the other arrays are accessed again, it will be the modified result

public static void main(String[] args) {
    
    
int[] arr1 = (1, 22);
int[] arr2 = arr1;
System.out.println(arr1[0]);
System.out.println(arr2[0]);

arr2[0]=0;
System.out.println(arr1[0]);
System.out.println(arr2[0]);
}

The picture comes from the Internet
The picture comes from the Internet


  1. A reference data type means that in Java, a variable stores a reference to an object rather than the object itself. This means that the variable points to the object in memory, rather than containing the value of the object itself. This differs from primitive data types, whose variables contain their own values.
    Includes classes, interfaces, arrays, and enumeration types. When you create an object, you actually allocate a block of memory on the heap to store the object, and return a reference to the memory address of the object. You can store that reference in a variable and use that variable to access the object. // 声明一个类类型的变量 MyClass obj;· ·// 创建一个对象并将其分配给变量 obj = new MyClass();· ·// 访问对象的属性和方法 obj.myMethod(); ↩︎

  2. This is because the length of the array is fixed, and the index of the array starts from 0, so the index of the last element is the length of the array minus 1. Therefore, the length of the array -1 is used as the end index of the array to ensure that there will be no Access to the memory space outside the array, thus ensuring the security of the program. ↩︎

Guess you like

Origin blog.csdn.net/m0_74154295/article/details/131076841