When I delete 1 object from ArrayList in Java. What will happen next?

I have a simple arraialist: ..

ArrayList<SP> sps = new ArrayList<SP>();
sps.add(new SP("1"));
sps.add(new SP("2"));
sps.add(new SP("3"));

.. When I remove 1 object from this list. What will happen next? Does this list simply delete the link to this object and then automatically release this memory zone (because nothing referenced this memory about this object) or was this object released directly from this memory zone with this list?

P / s: Sorry for my bad english.

+5
source share
4 answers

ArrayList.remove(), ( ). , .

, , - , , .

+9

, ArrayList, .

ArrayList.remove(), ArrayList. , .

, , , .

:

ArrayList<Integer> example = otherArrayList; // {2,3,10,6}
example.remove(1);                           // Remove second element
System.out.println(example.toString());

> [2, 10, 6] 
// The space to which '3' is allocated to is now eligible for GC

, GC:

ArrayList<Integer> example = otherArrayList; // {2,3,10,6}
int ref = example.get(1);                    // '3' is assigned to ref
example.remove(1);                           // Remove second element
System.out.println(example.toString());
System.out.print(ref);                      

> [2, 10, 6] 
> 3

/* Java is based on pass-by-value, but it passes references 
   when we pass existing object values. Which means the
   address space allocated for ref (and formerly example.get(1)) 
   is ineligible for GC.
*/ 
+4

, ( ) ?

JVM .

1) , GC.

2) , .
, Gargbage ( ) .

+1
ArrayList<SP> sps = new ArrayList<SP>();

, ArrayList SP, ArrayList SP, , SP.

, new SP("1");, object to SP, . , new SP("1");. , .

But in your ArrayList (for the same statement) there will be a link to accept the return from constructor of SP. Therefore, when you remove this object from the list, it loses its only link and gets the right to garbage collection.

Refernce: Call methods for a reference variable vs Call methods for a new object

0
source

Source: https://habr.com/ru/post/1670809/


All Articles