Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gc question: array of 10 ints a single object or 10 objects?

If i have an array say -
int[] a = new int[10];

does the Java GC when doing its collection see that as 10 objects or a single object?

Update:
so according to the given answers, looking at it from a GC perspective isnt it more efficient that instead of

List l; 
for(i =0;i<1000;i++)  
  l.add(new MyObj(343,"asdfasfd"));  

we should do -

int[] a; String[] b;
for(i =0;i<1000;i++)  {
  a[i]=343;
  b[i] = "asfasfsafsaf";
}

because in the first case we end up creating 1000 extra objects while in the 2nd case we do not.

like image 810
pdeva Avatar asked Dec 28 '25 00:12

pdeva


2 Answers

That's a single object. An array is one contiguous object and int is a primitive type, not an object type, so there are no objects created for the 10 ints.

// 1 object
int[] intArray = new int[10];

If you had an array of 10 Objects then there'd be 11 objects: the 10 objects plus the array. The array itself is still just a single object; it just happens to contain references to 10 other objects.

// 1 object...
Object[] objectArray = new Object[10];

// ...Plus 1 for each element once they are instantiated.
for (int i = 0; i < 10; ++i) {
    objectArray[i] = new Object();
}
like image 107
John Kugelman Avatar answered Dec 30 '25 14:12

John Kugelman


In terms of garbage collection, the array is a single object. If it's an array of primitive types like int, then there is only one object involved, and either the whole array is GC'd, or none of it is.

If you have an array of reference types, say Object, then that is one object for the array, plus up to 10 objects for the reference types referenced by the array (so an array of 10 reference could involve up to 11 objects). If you remove one of the objects from the array, say by setting it to null, or overwriting it with another object, and provided that object isn't referenced by any variable elsewhere, then it will become eligible for garbage collection. Example:

Object a = new Object(); // "Our Object"
Object[] array = new Object[10];
array[0] = a;
a = null; // a no longer references our Object
// now array[0] is the only reference to our Object
// and it isn't eligible for garbage collection yet
array[0] = null;
// Now our Object is eligible for garbage collection
like image 31
jameshales Avatar answered Dec 30 '25 14:12

jameshales



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!