Creando una lista de objetos en Java

So I was thinking of creating a list of objects like this

ArrayList<Obj> lst = new ArrayList<Obj>(10);
for (int i = 0; i < 10; i++) {
  Obj elem = new Obj();

Is this legal or do I have to worry about Object 1 getting trashed when the elem reference starts pointing to Object 2? If it's illegal, how might I do it otherwise? Is there a way to automatically generate ten different reference names?

preguntado el 09 de marzo de 12 a las 23:03

No you only have to worry about Object 1 getting trashed when there are no references left to the lst structure. The elem reference is "fresh" each time. -

Your two lines inside the loop can also be written as lst.add(new Obj()); -

3 Respuestas

Garbage Collector will remove objects only when there are no references pointing to it. In your case, your list will be pointing to 10 distinct Objeto objects and they are safe until you lose reference to LST Objeto.

Respondido el 22 de enero de 13 a las 03:01

It's perfectly legal. Your ArrayList will contain a reference to the object you just created, so it will not be GCed.

respondido 09 mar '12, 23:03

Your approach is perfectly valid. You will end up with a list of ten distinct objects.

respondido 09 mar '12, 23:03

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.