Home  >  Article  >  Java  >  array[]: a special class managed internally by the JVM itself

array[]: a special class managed internally by the JVM itself

DDD
DDDOriginal
2024-09-12 20:16:10859browse

The first way we are all introduced to the study of data structures in Java (and other languages) is through arrays. In Java, an array is a class, an object, a child of Object (as all classes are). However, it is a class with special treatment in the language.

Unlike common classes and objects, the syntax of arrays and their treatment is managed directly by the compiler and the JVM (Java Virtual Machine). This includes how arrays are allocated, manipulated and accessed. This class is not found directly in the source code.

Java automatically treats arrays as instances of this special class.

If you run the code below you will see the following outputs:

public class Main
{
    public static void main(String[] args) {
        int[] intArray = new int[5];
        System.out.println(intArray.getClass().getName());
        System.out.println(intArray.getClass().getSuperclass());
    }
}

[I
class java.lang.Object

This class name "[I" is just an automatically generated symbolic name, which the JVM uses to represent an array of integers (int[]). Each type has its own symbolic name:

array[]: uma classe especial gerenciada internamente pela própria JVM

The brackets "[" indicate dimensions. A one-dimensional array is represented by [, while a two-dimensional array is represented by [[, a three-dimensional array is represented by [[[... and so on.

Declaration

To declare and initialize an array, it is important to specify the data type and size of the object:

int[] intArray = new int[5]; //array de tamanho 5
char[] charArray = new char[]{'a', 'b', 'c'}; //o compilador entende que é um array de tamanho 3
double[] doubleArray = {1.2, 1.3, 1.4, 1.5}; //o compilador entende que é um array de tamanho 4

Java allows you to put square brackets in the variable name instead of the type, for example: int intArray[] = new int[5]. However, this is not recommended, as it deviates from convention.

Data stored within arrays can be allocated in memory "contiguously", that is, sequentially, by the JVM. To access data, indexes are used and the first index of an array is always 0 in Java.

For example, to access the letter 'a' of the charArray above, you need to search for it by charArray[0]. The letter 'b', in turn, is in charArray[1] and the letter 'c', in charArray[2]. If you try to access an index that does not exist in the array, you will receive an "IndexOutOfBounce" error. For example, in case I try to access the value in charArray[3].

The size of an array, once defined in the declaration, can never be changed. If I declared that charArray would have 3 elements, it will not contain more than that. Less yes... more no.

And here, an addendum. Unpopulated values ​​in an array will assume the same default value as the array's type. For example, in an integer array, empty values ​​will be filled with 0. In a boolean array, with false. In a string array, with null.

Just like the size, the type of an array cannot be changed. But it is possible to copy arrays with different types, if they are subtypes of the same type. Confusing, right? An example helps: Integer and Double are subtypes of Number. So...

Integer[] integerArray = {1, 2, 3};
Number[] numberArray = intgerArray;

This code is accepted by the compiler. However, caution is needed. If we do this here, we will generate a compilation error:

numberArray[0] = 1.2;

This is because integerArray and numberArray point to the same memory space. Even though numberArray supports a double as its first element, the integerArray does not and, therefore, the numberArray is not "allowed" to change the index value 0.

Memory

An array can always store data of the same type, accepting primitives and objects. If the array is made of integers, it will not accept char, double, float, String... only integer values.

The array itself is a class (albeit a special one) and, therefore, is stored on the Heap. In this way, the array stores a memory address which, in turn, contains the values ​​entered in the array.

A primitive array allocates contiguous blocks of memory to store values ​​directly, while an object array stores references (pointers) to objects, located elsewhere in memory.

This means that both arrays of primitive types (like int[]) and arrays of objects (like String[]) are stored on the heap. In the case of arrays of primitive types, the values ​​of the array elements are also stored directly on the heap, contiguous to the array itself. In the case of the object array, the objects pointed to by these references can be allocated in different locations on the heap.

Methods

All array classes have length and cloning methods. The first returns the size of the array and the second makes a copy of the array to another array (in this case, the pointer to the same memory address).

However, as a child of the Object class (as well as all classes in Java), the array also has the superclass methods: toString, equals and hashCode.

Using arrays behind the scenes, however, is what happens most in real life. Even though arrays are performant, it is much more complicated to iterate their elements and there are classes that make abstractions on top of arrays that make the programmer's life much simpler.

This is the case with the Arrays class (with capital letter). It basically packages arrays in a standard Java class and presents a series of very simple to implement methods for working with the data. The Arrays class has another powerful advantage: it works with dynamic allocation, so it is easier to deal with collections - after all, we rarely know the exact size of the array we may need. The Arrays class can expand the size of the collection on demand, without the programmer having to create new arrays (with lowercase letters) of larger sizes and copying data from the previous array, which suddenly became too small.

Arrays are also the basis of classes such as List, Stack and Queue (which are basically a wrap and include very good methods for dealing with data).

Have you ever stopped to think that String is a class that abstracts a char array?

array[]: uma classe especial gerenciada internamente pela própria JVM

The above is the detailed content of array[]: a special class managed internally by the JVM itself. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn