我正在尝试编写一个方法,该方法接受2个双精度的ArrayList,并返回set1中未在set2中找到的所有值。这些数字应在set3中返回。我不断遇到内存不足错误。谁能指出我正确的方向?
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;
}
最佳答案
某些循环可能不会像您期望的那样停止。
下面的代码片段将完成几乎与您尝试的相同的操作。
for (Double d : set1) {
if (!set2.contains(d)) {
set3.add(d);
}
}
更新:由于您说不能使用contains(),因此您可以自己执行检查:
for (Double d : set1) {
boolean found = false;
for (int i=0; i<set2.size() && !found; i++) {
if (d.equals(set2.get(i))) {
found = true;
}
}
if (!found) {
set3.add(d);
}
}
编辑:此外,您的代码中的问题在于行
if(count2 != set2.size()){
您应该用>更改!=,因为在count2小于set2的情况下,外部count变量将不会增加,从而导致无限循环,并在几秒钟后发生OutOfMemoryError。
另外,您的算法也不是100%正确,因为遍历第二个列表的循环不一致。您可以在下面看到while循环的类似方法:
int count = 0;
while (count < set1.size()) {
boolean inList = false;
int count2 = 0;
while (inList == false && count2 < set2.size()) {
if (set1.get(count).equals(set2.get(count2))) {
inList = true;
}
count2++;
}
if (!inList) {
set3.add(set1.get(count));
}
count++;
}