I’m trying to write a method that takes 2 ArrayLists of doubles and returns all the values in set1 that aren’t found in set2. These numbers should be returned in set3. I keep getting an out of memory error. Can anyone point me in the right direction?
ArrayList<Double> setDiff(ArrayList<Double> set1, ArrayList<Double> set2){
ArrayList<Double> set3 = new ArrayList<Double>();
int count = 0;
while(count < set1.size()){
boolean inList = false;
while(inList == false){
int count2 = 0;
while(count2 < set2.size() && set1.get(count) == set2.get(count2)){
count2++;
}
if(count2 != set2.size()){
set3.add(set1.get(count));
}
else{
inList = true;
count++;
}
}
}
return set3;
}
Some loop is likely not stopping as you would expect.
The following code snippet would accomplish pretty much the same you are trying to do.
UPDATE: since you say you cannot use contains(), you can perform the checks by yourself:
EDIT: Furthermore, the problem in your code lies in the line
You should change != with >, since in the case of being count2 less than set2, the external count variable will not increase, resulting in an infinite loop, and after a few seconds, an OutOfMemoryError.
Also, your algorithm wasn’t 100% correct either, since the looping through the second list was not consistent. You can see a similar approach with while-loops below: