Arrays are objects
To documentation about Arrays says that they are objects that contain a fixed number of values of a certain type.
This can be proved by the following code:
String[] array = new String[10];
System.out.println(array instanceof Object);
The result is:
true
Arrays have multiple personalities
There is a reason for the special syntax in creating arrays. Each instantiated array with a different type generates a new class dynamically.
Suppose the creation of two arrays below:
String[] array1 = new String[10];
Integer[] array2 = new Integer[10];
If you print the name of the classes of these objects like this:
System.out.println(array1.getClass().getName());
System.out.println(array2.getClass().getName());
You will see that they return different values, as follows:
[Ljava.lang.String;
[Ljava.lang.Integer;
We can verify that the types are incompatible with each other:
System.out.println(array1.getClass().isAssignableFrom(array2.getClass()));
From what we get:
false
Lists are different
As a counterexample, lists using genetics nay have the same behaviour.
Consider the lists:
List<String> list1 = new ArrayList<>();
List<Integer> list2 = new ArrayList<>();
If we print the classes, we see that the type Erasure was effective because they are identical:
java.util.Arraylist
java.util.Arraylist
And we can verify that they are compatible with each other using:
System.out.println(list1.getClass().isAssignableFrom(list2.getClass()));
From which we get:
true
Builder
Arrays do not have constructors in the traditional sense, that is, you cannot extend the class and override the constructor.
However, as every object it will have its state initialized at some point by the Virtual Machine.
This can be a disadvantage from the point of view of language flexibility, just as it occurs with primitive types. On the other hand, this allows the JVM to optimize array allocation without relying on Java code.
Storage
Arrays allocate a continuous chunk of memory, whose positions are accessed through the index. Each position contains a element.
The elements directly contain the values in the case of primitive types, while objects are stored as references. This causes elements to be initialized with the default value of that type in a new array of primitives, while object arrays have their elements initialized with null
.
References vs. Pointers
There is already content here in the OS about this, but basically a reference is something that always points to an object and allows access to it only through the interface or type of reference used.
You cannot point a reference to an arbitrary position in memory or perform mathematical operations on them.
Points to the same place when you do int a = 6; String a = "";
– Marco Souza