We have learned about array, which is a reference type. This article describes the knowledge points of Array Memory Allocation in detail. An array is used to store data of the same data type. Once Initialization is complete, the occupied space is fixed. Even if an element is cleared, its space is retained, therefore, the array length cannot be changed. When only one array variable (int [] numbers) is defined, the variable does not point to any valid memory, so the length of the array cannot be specified, it can only be used after array initialization (allocating memory space for array elements. Array Initialization is divided into static initialization (the value of the array element is specified at the time of definition, and the length of the array cannot be specified at this time) and dynamic initialization (only the length of the array is specified, and the initial value is allocated by the system ).
// Static Initialization
Int [] numbers = new int [] {3, 5, 12, 8, 7 };
String [] names = {"Miracle", "Miracle He"}; // use the simplified form of static Initialization
// Dynamic Initialization
Int [] numbers = new int [5];
String [] names = new String [2];
We recommend that you do not mix static initialization and dynamic initialization, that is, do not specify both the length of the array and the value of each element. After initialization, you can set the index position (0 ~ Array. length-1) to access the array elements. When dynamic Initialization is used, if no value is specified for the corresponding index bit, the system will specify the default value for the corresponding data type (INTEGER: 0, floating point: 0.0, the character is '\ u0000', the boolean type is false, and the reference type is null ).
Public class TestArray {
Public static void main (String [] args ){
String [] names = new String [3];
Names [0] = "Miracle ";
Names [1] = "Miracle He ";
// The following code outputs Miracle He null
// You can also use foreach to traverse
For (String name: names ){
System. out. print (name + "");
}
}
}
Note: in java, the keyword foreach is not found. Its syntax is for (type item: items), but foreach can only be used to traverse element values and cannot be changed, you must use.
Public class TestForEach {
Public static void main (String [] args ){
Int [] numbers = {3, 5, 12, 8, 7 };
For (int number: numbers ){
Int num = number * 10;
System. out. print (num + ",");
}
System. out. println ("");
// Numbers still does not change (if changed to for, it will change)
For (int I = 0; I <numbers. length; I ++ ){
System. out. print (numbers [I] + ",");
}
}
}
The above briefly introduces the initialization and Application of arrays. Next we will introduce in detail the storage form of arrays (array references and array elements) in memory. First, it is concluded that the array reference variables are stored in the stack memory (stack), and the array elements are stored in the heap memory (heap, by pointing the pointer in the stack memory to the location of the corresponding element in the heap memory, it indicates the storage format of the array at this time.
So what is stack memory and heap memory? I will give examples to illustrate them one by one. When a method is executed, the method creates its own memory stack to add the variables defined in the method to the memory stack one by one, when the execution ends, the method's memory stack is also destroyed. We say that all variables are stored in the stack memory, that is, they die with the death of the storage entity; otherwise, when we create an object, this object is saved to the runtime data area for reuse (because the creation cost is high) and will not die with the execution method ending, at the same time, this object can be referenced by other objects. Only when this object is not referenced by any referenced variable will garbage collection be collected at an appropriate time point, we say that the runtime data zone to which the variable points exists in the heap memory.
Only when the data type is compatible (that is, belongs to the same data type system and complies with the rule of low-to-high priority) Can the array reference be passed to another array reference, but still cannot change the array length (just adjust the pointer pointing to the array reference ).
Public class TestArrayLength {
Public static void main (String [] args ){
Int [] numbers = {3, 5, 12 };
Int [] digits = new int [4];
System. out. println ("digits array length:" + digits. length); // 4
For (int number: numbers ){
System. out. print (number + ","); // 3,5, 12,
}
System. out. println ("");
For (int digit: digits ){
System. out. print (digit + ","); // 0, 0, 0,
}
System. out. println ("");
Digits = numbers;
System. out. println ("digits array length:" + digits. length); // 3
}
}
Although the length of the seemingly digits array seems to be changed from 4 to 3, the numbers and digits actually point to the same array, and digits itself loses reference and turns into garbage, wait for garbage collection to be recycled (but its length is still 4), as shown in the internal operating mechanism.
Therefore, when we look at an array (or other referenced variables), we usually think of two parts: the array references the variable and the array element itself, and the data element is stored in the heap memory, it can only be accessed through array reference variables.
From the above example, we can see that the array stores the basic type. In fact, the array can also store the reference type. The memory distribution for storing basic types has been explained, while the memory distribution for storing reference types is relatively complicated. Let's look at a very simple program.
Public class TestPrimitiveArray {
Public static void main (String [] args ){
// 1. Define an array
Int [] numbers;
// 2. allocate memory space
Numbers = new int [4];
// 3. Specify a value for the array element
For (int I = 0; I <numbers. length; I ++ ){
Numbers [I] = I * 10;
}
}
}
Memory distribution according to the above steps:
It can be seen that the array elements are directly stored in the heap memory. When operating the array elements, they are actually basic types of variables. Next, let's look at another program:
Class Person {
Public int age;
Public String name;
Public void display (){
System. out. println (name + "is:" + age );
}
}
Public class TestReferenceArray {
Public static void main (String [] args ){
// 1. Define an array
Person [] persons;
// 2. allocate memory space
Persons = new Person [2];
// 3. Specify a value for the array element
Person p1 = new Person ();
P1.age = 28;
P1.name = "Miracle ";
Person p2 = new Person ();
P2.age = 30;
P2.name = "Miracle He ";
Persons [0] = p1;
Persons [1] = p2;
// Output element value
For (Person p: persons ){
P. display ();
}
}
}
The storage of the array element as the reference type in the memory is different from the basic type. In this case, the array element still stores the reference and points to another memory to store valid data.
Speaking of this, I wonder whether a friend has asked: What is the multi-dimensional array of Java? My answer is: yes. Why? At the underlying layer, array elements can store reference types, including arrays. In other words, the array element can also contain arrays (such as int [] [] numbers = new int [length] []), that is, a two-dimensional array can be treated as a one-dimensional array (the length of the array is length, you can also specify the length of multiple dimensions (for example, int [] [] matrix = new int [length] [width]). However, you must specify at least the length of the leftmost array. From this we can conclude that any multi-dimensional array (dimension: n, n> 1) is treated as a one-dimensional array, and its array elements are n-1-dimensional arrays.
Public class TestMultiArray {
Public static void main (String [] args ){
// 1. Define a two-dimensional array
Int [] [] numbers;
// 2. allocate memory space
Numbers = new int [3] [];
// Process numbers as a one-dimensional array
For (int I = 0; I <numbers. length; I ++ ){
System. out. print (numbers [I] + ","); // null, null, null
}
System. out. println ("");
// 3. Specify a value for the array element
Numbers [0] = new int [2];
Numbers [0] [1] = 1;
For (int I = 0; I <numbers [0]. length; I ++ ){
System. out. print (numbers [0] [I] + ","); // 0, 1
}
}
}
Finally, we will briefly introduce the static methods of Arrays (located in java. util): binarySearch, copyOf, copyOfRange, equals, fill, sort, and toString (for details, see JDK ).
Import java. util. Arrays;
Public class TestArrays {
Public static void main (String [] args ){
Int [] a = {3, 4, 5, 6 };
Int [] B = {3, 4, 5, 6 };
System. out. println ("a and B are equal:" + Arrays. equals (a, B); // true
System. out. println ("5 position in a:" + Arrays. binarySearch (a, 5); // 2
Int [] c = Arrays. copyOf (a, 6 );
System. out. println ("a and c are equal:" + Arrays. equals (a, c); // false
System. out. println ("c element:" + Arrays. toString (c ); //,
Arrays. fill (c, 2, 4, 1); // assign values from 3rd to 5th elements (not included) in c to 1.
System. out. println ("c element:" + Arrays. toString (c ); //,
Arrays. sort (c );
System. out. println ("c element:" + Arrays. toString (c ); //,
}
}
Next, we will provide two examples of the actual application scenarios of arrays.
Convert numbers to RMB capital (simplified)
Import java. util. Arrays;
Public class NumberToRMB {
Private String [] numbers = {"zero", "one", "two", "three", "Si", "Wu", "Lu", "Lu ", "identifier", "identifier "};
Private String [] units = {"pick", "success", "success "};
Private String [] divide (double number ){
Long zheng = (long) number;
Long xiao = Math. round (number-zheng) * 100 );
Return new String [] {zheng + "", String. valueOf (xiao )};
}
Private String toRMBString (String str ){
String money = "";
For (int I = 0, len = str. length (); I <len; I ++ ){
Int num = str. charAt (I)-48;
If (I! = Len-1 & num! = 0 ){
Money + = numbers [num] + units [len-2-I];
} Else {
Money + = numbers [num];
}
}
Return money;
}
Public static void main (String [] args ){
NumberToRMB RMB = new NumberToRMB ();
System. out. println (Arrays. toString (RMB. divide (2346.789 )));
System. out. println (RMB. toRMBString ("2346 "));
}
}
Wuziqi game implementation (Simplified Version)
Import java. io .*;
Public class WZQ {
// Define a two-dimensional array as a chessboard
Private String [] [] board;
// Define the size of the Board
Private static int BOARD_SIZE = 15;
// Initialize the chessboard
Private void initBoard (){
Board = new String [BOARD_SIZE] [BOARD_SIZE];
For (int I = 0; I <BOARD_SIZE; I ++ ){
For (int j = 0; j <BOARD_SIZE; j ++ ){
Board [I] [j] = "+ ";
}
}
}
// Print the chessboard
Private void printBoard (){
For (int I = 0; I <BOARD_SIZE; I ++ ){
For (int j = 0; j <BOARD_SIZE; j ++ ){
System. out. print (board [I] [j]);
}
System. out. println ("");
}
}
// Start playing chess
Public void play () throws Exception {
InitBoard ();
PrintBoard ();
// Obtain keyboard input
BufferedReader br = new BufferedReader (new InputStreamReader (System. in ));
String input = null;
Do {
If (input! = Null ){
String [] pos = input. split (",");
Int x = Integer. parseInt (pos [0]);
Int y = Integer. parseInt (pos [1]);
Board [x-1] [y-1] = "● ";
PrintBoard ();
}
System. out. print ("Enter the coordinates of your game (in the form of x and y ):");
} While (input = br. readLine ())! = Null );
}
Public static void main (String [] args) throws Exception {
WZQ wzq = new WZQ ();
Wzq. play ();
}