Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>[If you want some ready-to-use code, please scroll to my "Edit3" (after the cut). The rest is here for posterity.]</p> <p>To flesh out <a href="https://stackoverflow.com/a/112507/13">Dustman's idea</a>:</p> <pre><code>List&lt;String&gt; list = new ArrayList&lt;String&gt;(Arrays.asList(array)); list.removeAll(Arrays.asList("a")); array = list.toArray(array); </code></pre> <p>Edit: I'm now using <code>Arrays.asList</code> instead of <code>Collections.singleton</code>: singleton is limited to one entry, whereas the <code>asList</code> approach allows you to add other strings to filter out later: <code>Arrays.asList("a", "b", "c")</code>.</p> <p>Edit2: The above approach retains the same array (so the array is still the same length); the element after the last is set to null. If you want a <em>new</em> array sized exactly as required, use this instead:</p> <pre><code>array = list.toArray(new String[0]); </code></pre> <hr> <p>Edit3: If you use this code on a frequent basis in the same class, you may wish to consider adding this to your class:</p> <pre><code>private static final String[] EMPTY_STRING_ARRAY = new String[0]; </code></pre> <p>Then the function becomes:</p> <pre><code>List&lt;String&gt; list = new ArrayList&lt;&gt;(); Collections.addAll(list, array); list.removeAll(Arrays.asList("a")); array = list.toArray(EMPTY_STRING_ARRAY); </code></pre> <p>This will then stop littering your heap with useless empty string arrays that would otherwise be <code>new</code>ed each time your function is called.</p> <p>cynicalman's suggestion (see comments) will also help with the heap littering, and for fairness I should mention it:</p> <pre><code>array = list.toArray(new String[list.size()]); </code></pre> <p>I prefer my approach, because it may be easier to get the explicit size wrong (e.g., calling <code>size()</code> on the wrong list).</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