Note that there are some explanatory texts on larger screens.

plurals
  1. POMerging two arrayLists into a new arrayList, with no duplicates and in order, in Java
    primarykey
    data
    text
    <p>I am trying to "combine" two arrayLists, producing a new arrayList that contains all the numbers in the two combined arrayLists, but without any duplicate elements and they should be in order. I came up with this code below. I run through it and it makes sense to me, but Im not sure if I can be using &lt; or > to compare get(i)'s in arrayLists. I am adding all the elements in array1 into the plusArray. Then I am going through the plusArray and comparing it to array2 to see if any of array2's elements exist inside plusArray. If they do I am doing nothing, but if they dont then I am trying to add it in its correct position. Perhaps my nested for loops being used incorrectly? Note: The ArrayLists are presorted by the user in increasing order.</p> <pre><code> ArrayList&lt;Integer&gt; plusArray = new ArrayList&lt;Integer&gt;(); for(int i = 0; i &lt; array1.size(); i++){ plusArray.add(array1.get(i)); } for(int i = 0; i &lt; plusArray.size(); i++){ for(int j = 0; j &lt; array2.size(); j++){ if(array2.get(j) &lt; plusArray.get(i)){ plusArray.add(i,array2.get(j)); } else if(plusArray.get(i).equals(array2.get(j))){ ; } else if(array2.get(j) &gt; plusArray.get(i)){ plusArray.add(i, array2.get(j)); } } </code></pre> <p>UPDATE: I dont get the exception below anymore. Instead it seems the program runs forever. I changed the location of where to add the elements in the &lt; and > conditions. /// Here is the exception that I get when my array lists are: IntSet 1: { 1 2 } IntSet 2: { 1 3 4 }</p> <pre><code>Exception in thread "main" java.lang.OutOfMemoryError: Java heap space at java.util.Arrays.copyOf(Unknown Source) at java.util.Arrays.copyOf(Unknown Source) at java.util.ArrayList.grow(Unknown Source) at java.util.ArrayList.ensureCapacityInternal(Unknown Source) at java.util.ArrayList.add(Unknown Source) at IntSet.plus(IntSet.java:92) at IntSetDriver.main(IntSetDriver.java:61) </code></pre>
    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.
 

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