views:

176

answers:

3

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.

+8  A: 

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();
}
John Kugelman
+2  A: 

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
_jameshales
+2  A: 

A real answer (in the sense of, one that would tell you whether the first case is actually more expensive to garbage-collect) would take somebody who knows the garbage collector a lot better than I do.

But is it really that important to try to fake out the garbage collector? The life cycles of the Strings and MyObjects will be pretty much the same, and GC is pretty smart. It's just possible you could be slightly improving your garbage collection time, but what you're paying for that, having to manually manage both arrays -- basically giving up on OO -- is a nasty increase in code complexity and probable bugs.

David Moles
I agree - unless you are having a turnover of *billions* of objects which makes your GC work really hard - don't mess with it.
David Rabinowitz