Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java array of Object that does not require new: allocated contiguosly

In Java you declare an array and then you call new to allocate space. so that a class with 4 named integers takes less space and has better locality than an array of size 4.

Is there any way to have an array of 4 elements, but have it allocated the same way as named vaiables a1, a2, a3, a4

For those that know C++, this is the same as asking for int x[4] as opposed to int *x

class X
{
   int x1;
   int x2;
   int x3;
   int x4;
};

[ Class OID ][x1][x2][x3][x4] = 1 ref + 4 int

class Y
{
   int y[];
};

y=new int[4];

[ Class OID ][Y] ======> [Array OID][Array Size][y][y][y][y] = 3 ref + size + 4 int
like image 252
Glenn Teitelbaum Avatar asked May 29 '26 16:05

Glenn Teitelbaum


1 Answers

Starting with Java 6, under ideal circumstances, objects are actually allocated on the stack rather than on the heap -- in other words, just what you're asking for. In general, this is attempted for objects whose references don't leave the scope in which they are created. So the truth is, in fact, that sometimes "new" is absolutely free! Although it may seem that Java code is verbose and inefficient, there are several layers of optimizing compilers that turn what you write into surprisingly efficient machine code.

like image 185
Ernest Friedman-Hill Avatar answered Jun 01 '26 05:06

Ernest Friedman-Hill