从Vector中删除对象后应该明确删除它吗?

Fai*_*dur 5 java garbage-collection

假设我有一个Vector v 包含100个类的对象,Scenario它由10种不同类型的对象组成.为了永久删除ScenarioVector v的索引5处的所有对象,以下哪一种方法是正确的.

1.   v.removeElementAt(5);
Run Code Online (Sandbox Code Playgroud)

要么:

2.   Scenario s=(Scenario) v.elementAt(5); 
     v.removeElementAt(5);
     s=null;
Run Code Online (Sandbox Code Playgroud)

要么:

3.   Scenario s=(Scenario) v.elementAt(5); 
     s.makeAllObjectsNull();//explicitly assign null to 10 objects inside Scenario e.g. object1=null object2=null and so on
     v.removeElementAt(5);
     s=null;
Run Code Online (Sandbox Code Playgroud)

Sal*_*lah 3

从 Vector 中删除对象后是否需要显式删除该对象?简而言之,所有没有任何来自另一个对象的引用的对象都是清晰可见的GC

因此,您的代码的任何情况都满足该条件,那么该对象将为GC.

例如,如果 Scenario 对象仅具有该向量的引用,则:

v.removeElementAt(5);
Run Code Online (Sandbox Code Playgroud)

唯一的参考资料已经消失,并且将清晰可见GC

这里要说的还有一件事。当你这样做时:

 Scenario s = (Scenario) v.elementAt(5); 
 v.removeElementAt(5);
 s = null;
Run Code Online (Sandbox Code Playgroud)

您刚刚声明了另一个引用s,然后将其设置为null,因此没有必要这样做。