Why array elements must be of the same type

ArrayDS requires all its members to have the same time. Java throws an ArrayStoreException when an attempt has been made to store the wrong type of an object in an array of objects. Do not remember what does C++.

I correctly understand that it is important to have all objects of the same type in the array , because it guarantees constant access to the time element through the following two operations:

1) element size * element index = offset
2) array pointer address + offset

If the objects have different types and therefore different sizes, the above formula will not work.

+4
source share
3 answers

, . , .

, void, . , ++, do

void * a[N]

a[i] = (void *)(&YourClass)

, Object[] java.

+4

: , .

: , Java (, ++), .

; "" .

: Java , [] - . , , .

: ++ . ; .

Java, , .

: Java ++ ( ); "" . : , , , "" .

, : , , , . , .

+5

++ ( ) , , (, x[i]), , ,...).

int x[3] = { 1,2,3 };  // array of 3 int values, each being properly aligned concerning processor architecture;
myObjectType objs[10]; // array of 10 objects of type myObjectType, each being default initialised (probably the default constructor), each being properly aligned
myObjectType *objs[10]; // array of 10 pointers to objects of type myObjectType (including subclasses of myObjectType; allowing dynamic binding and polymorphism). Note: all pointers have the same size, the object to which they point may differ insize.

int *intptr = x;
bool isEqual= (intptr[2] == x[2]); // gives true
intptr += 2; // increases the pointer by "2*sizeof(int)" bytes.

, , : ; , , , , , , , .

+2
source

Source: https://habr.com/ru/post/1675331/


All Articles