Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can call the <code>clear</code> method on the <code>List</code> object. That will remove all elements without the need to create a new instance. The documentation is <a href="http://docs.oracle.com/javase/6/docs/api/java/util/List.html#clear%28%29" rel="nofollow">here</a>. </p> <p><b> Just to note on object references </b></p> <blockquote> <p>when i finish and want to create new instance in specObject I want to clear it before ,how should I do that?</p> </blockquote> <p>Let's say you have a list:</p> <pre><code>ArrayList&lt;String&gt; strings = new ArrayList&lt;String&gt;(); </code></pre> <p>If you add some string objects to this list:</p> <pre><code>strings.add("Hello"); strings.add("There"); strings.add("StackOverflow"); </code></pre> <p>Then you nullify the <code>strings</code> object.</p> <pre><code>strings = null; </code></pre> <p>You have effectively removed all of the elements inside the list? Why? Well when you declare <code>ArrayList&lt;String&gt; strings;</code>, you're not creating a new object. You're creating a new reference (pointer) to an object. To illustrate this:</p> <pre><code>String s = "Hello"; String s2 = s; // s2 points to the same object that s points to. String s3 = "Another String"; // S3 points to a different object. </code></pre> <p>The one exception to this rule is if you declare:</p> <pre><code>String s = "Hello"; String s2 = "Hello"; // s2 will point to the same object as s. </code></pre> <p>When an object isn't pointed to by anything, it is removed by the Garbage Collector. So effectively, if you declare:</p> <pre><code>strings = null; </code></pre> <p>You're removing all of the <code>String</code> child objects that you added to.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload