Home > other >  Does Java remove objects from the heap after a for loop in which that object was created and never u
Does Java remove objects from the heap after a for loop in which that object was created and never u

Time:10-31

I have a simple for loop in which I create new objects and save to list. After this loop I never used these objects again. Will Java remove these objects from heap or keep them alive before method end because of there are (in stack area) will be several local variables of OrderItem type?

for (int i = 0; i < arr.length; i  ) {
            OrderItem item = new OrderItem();
            item.setProduct(product);
            item.setQuantity(entry.getValue());
            orderItemList.add(item);
        }

Or these objects will live in heap until end of a method (method frame). But what if move declaration of OrderItem item outside the loop.

OrderItem item;
for (int i = 0; i < arr.length; i  ) {
            item = new OrderItem();
            item.setProduct(someValue);
            item.setQuantity(someValue);
            orderItemList.add(item);
        }

As I understand correctly, in this case in stack area there is only one local variable of OrderItem type and on each loop iteration this variable will reference to new object. And for objects from previous iterations there are no references and these objects should be removed from heap.

CodePudding user response:

Will Java remove these objects from heap or keep them alive before method end because of there are (in stack area) will be several local variables of OrderItem type?

I assume that your orderItemList is ArrayList<OrderItem> in which case adding an OrderItem to orderItemList should only add a reference pointing to the currently created item to your list rather than copying the whole object (as discussed in the linked post). Then as long as orderItemList is around its OrderItems should stay in the heap.

https://stackoverflow.com/questions/7080546/add-an-object-to-an-arraylist-and-modify-it-later#:~:text=The reference you added will,the reference to the object.

After this loop i never used these objects again.

If you are using orderItemList again, which I assume you do, since otherwise it is not clear why the list would be created in the first place, you should be using also OrderItems added to it again.

  • Related