Array and reference type memory allocations

Source: Internet
Author: User
Tags array length garbage collection type null

In the previous article, we have already understood the array, it is a reference type, this article will introduce the array memory allocation and so on the knowledge point in detail. Arrays are used to store data of the same data type, and once initialized, the space is fixed, even if an element is emptied, but its space remains, so the length of the array cannot be changed. When you define only an array variable (int[] numbers), the variable does not point to any valid memory, so you cannot specify the length of the array, which is only available after the arrays are initialized (the array element allocates memory space). Array initialization is divided into static initialization (specifying the value of an array element when defined, not specifying the length of the array at this time) and dynamic initialization (specifying the length of the array and allocating the initial value by the system).

Static initialization
int[] numbers = new int[] {3, 5, 8, 7};
String[] names = {"Miracle", "Miracle he"};//using a simplified form of static initialization
Dynamic initialization
int[] numbers = new int[5];
string[] names = new string[2];

It is recommended that you do not mix static initialization and dynamic initialization, that is, you do not specify the length of the array and specify the value of each element. When the initialization is complete, the array elements can be accessed by index position (0~array.length-1). When using dynamic initialization, such as when a value is not specified at the corresponding index bit, the system specifies the default value for the corresponding data type (integer 0, floating-point number 0.0, character ' \u0000 ', Boolean type false, reference type 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 Miracle he null
        /* for
        (int i = 0; i < names.length;i++) {
            System.out.print (Names[i] + "") ;
        }
        *
        ///You can also use foreach to traverse for
        (String name:names) {
            System.out.print (name + "");
}}}

Note that there is no foreach keyword in Java whose syntax is for (type Item:items), but foreach can only be used to traverse the value of an element without changing it, and must be implemented with a for.

public class Testforeach {public
    static void Main (string[] args) {
        int[] numbers = {3, 5, 8, 7};
        for (int number:numbers) {
            int num = number *;
            System.out.print (num + ",");
        }
        System.out.println ("");
        Numbers is still unchanged (if replaced with for 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, and then details the way in which arrays (array references and arrays) are stored in memory. First, the conclusion is that the array reference variables are stored in stack memory (stacks), the array elements are stored in heap memory (heap), through the stack in the memory of the pointer to the corresponding elements in the heap memory location to achieve access, the following figure to illustrate the storage form of the array at this time.

So what is stack memory and heap memory? I give an example to explain. When the method is executed, the method builds its own memory stack. To add a variable to the memory stack for the internal definition of the method, the memory stack of the method is also destroyed when the execution ends, and we say that all variables are stored in the stack memory, which dies as the host body dies; Conversely, when we create an object, This object is saved to the runtime data area. So that it can be reused (because of the high cost of creation), it will not die out with the end of the execution method, and the object is also referenced by other objects, only when the object is not referenced by any reference variables, the garbage collection at the appropriate point in time to recycle, We say that the Run-time data area that the variable points to is in heap memory.

You can pass an array reference to another array reference only if the type is compatible (that is, it belongs to the same data type system and follows the precedence from low to high), but you still cannot change the length of the array (just to adjust the pointer to the array reference).

public class Testarraylength {public
    static void Main (string[] args) {
        int[] numbers = {3, 5,};
        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,0,
        }
        System.out.println ("");
        digits = numbers;
        SYSTEM.OUT.PRINTLN ("Digits array length:" + digits.length);//3
    }
}

Although seemingly digits array lengths seem to change from 4 to 3, only numbers and digits point to the same array, and digits itself loses reference and becomes garbage, waits for garbage collection to be reclaimed (but its length is still 4), but its internal operating mechanism is shown in the following illustration.

So when we look at an array (or some other reference variable), it's usually considered two parts: the array reference variable and the group element itself, while the data element is stored in heap memory and can only be accessed through an array reference variable.

As you can see from the example above, the base type is stored in the array, but the reference type is also stored in the array. The memory distribution of the underlying type has been explained, while the memory distribution of the reference type is relatively complex. Look at a very simple procedure.

public class Testprimitivearray {public
    static void Main (string[] args) {
        //1. Definition array
        int[] numbers;
        2. Allocating memory space
        numbers = new int[4];
        3. Specify value for array element for
        (int i = 0;i < numbers.length;i++) {
            Numbers[i] = i *;}
    }}

In the memory distribution diagram of the steps above:

You can see from the diagram that the array elements are stored directly in the heap memory, and when manipulating the array elements, they are actually variables that manipulate the basic type. Next look at a program:

class person {public int age;
    public String name;
    The age of the public void display () {System.out.println (name +) is: "+ aging"; } public class Testreferencearray {public static void main (string[] args) {//1. Define array person[] Perso
        ns
        2. Allocating 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;
        The value of the output element for (person p:persons) {p.display (); }
    }
}

For an array element to be stored in memory with a reference type different from the base type, the array element still holds the reference and points to another memory in which valid data is stored. Speaking of this, I do not know whether a friend to ask: Java multidimensional array is what. My answer is: can have. Why, then? From the bottom up, array elements can hold reference types, including arrays. That is, an array (such as int[][] numbers = new int[length][] can also be included inside an array element, or a two-dimensional array can be treated as a one-dimensional array (length of the array), or you can specify the length of multiple dimensions (such as int[][) Matrix = new Int[length][width]), but at least the leftmost length of the array must be specified. From this we conclude that any multidimensional array (dimension n,n>1) is treated as a one-dimensional array whose array elements are n-1 dimension arrays.

public class Testmultiarray {
    

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.