Note that there are some explanatory texts on larger screens.

plurals
  1. POArrayList or several for loops?
    primarykey
    data
    text
    <p>I know this might be simple, I have a situation where I need to decide between using four for-loops to (two to count and remove null elements, two to add elements) merge two String arrays or use two for-loops with an ArrayList and convert the ArrayList to array using ArrayList.toArray().</p> <p>Performance wise are there any differences between these two approaches?</p> <p>EDIT</p> <p>I had to drop the ArrayList with generics approach because of compatibility issues. But here is the earlier code.</p> <pre><code>List&lt;String&gt; newList = new ArrayList&lt;String&gt;(); for (String element : array1) { if (element != null) { newList.add(element); } } for (String element : array2) { if (element != null) { newList.add(element); } } return newList.toArray(new String[]{}); </code></pre> <p>I wrote a new code with one loop, but I think I might be mentally killing the next one reading this code. </p> <pre><code>String[] newArr = new String[array1.length + array2.length]; int n = 0; for (int i = 0; i &lt; newArr.length; i++) { if (i &lt; array1.length &amp;&amp; array1[i] != null) { newArr[n] = array1[i]; n++; } if (i &gt;= array1.length) { int a = 0; if (array1.length &lt; array2.length) { a = (i - array1.length) + (array2.length - array1.length); } else { a = i - array1.length; } if (array2[a] != null) { newArr[n] = array2[a]; n++; } } } return newArr; </code></pre> <p>And finally got to know that null element check won't be needed so went ahead with this simple code.</p> <pre><code>String[] newArr = new String[array1.length + array2.length]; System.arraycopy(array1, 0, newArr, 0, array1.length); System.arraycopy(array2, 0, newArr, array1.length, array2.length); return newArr; </code></pre> <p>I guess from the discussion below the second method is the better performing one. </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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