How does an array work internally in Java?

This request is posted to basically understand things like

  • An object is an instance of a class or an array;

  • An array is a subclass of a class Object

    ;

  • Anything that is a non-primitive instance is an object in Java.

Here is my understanding of working with arrays in Java.

Given the below program,

/* dummy.java */
class C {
    private int i; 
    public C() {
        i = 1;
        System.out.println("Am in constructor");
    }
}
public class dummy {
    public static void main(String[] args) {
        C[] c = new C[2]; // Line 11
        c[0] = new C();
        System.out.println(c);
    }
}

      

The type object is class [LC

created at runtime after startup,

C[] c = new C[2]; //Line 11

      

In the above code. class [LC

is a direct subclass of the class Object

. The control variable c

points to this object (shown in the red border below) after being run Line 12

in the above code. Control variables are located on the stack, and the type object class C

will reside on the heap.

enter image description here

For the below change line 11 & 12

in the above code

C[][] c = new C[2][2];
c[0][0] = new C();

      

will make a presentation like below.

enter image description here

Do I understand correctly? If so, can you explain more about using class [LC

at runtime to create an object?

Note: C[].class

gives the actual runtime type that class [LC

.

+3


source to share


1 answer


To answer your question: yes, in Java (and C #), almost everything is broken down into several discrete chunks of memory that are accessed by pointers. This is not only your two-dimensional array, but any embedded object inside your C object. In C ++, if you have an array (one-dimensional or not) of 10 objects, and each of those objects contains 10 embedded objects, you can select all it's using one piece of memory. In C # and Java you will have at least 101 memory allocations to store all of this (if all embedded objects are simple objects) in the case of a monomeric array, etc. In the case of a multidimensional array.



However, this explosion of chunks of memory should not be seen as something very bad, because it frees you from the difficulty of managing your own memory allocation, as you can with C / C ++ and in most cases, the power of any modern processor is usually sufficient. to pull it forward with sufficient speed.

+1


source







All Articles