我有以下数组列表
cd1 = [3,5,7,10,15,16]
cd2 = [4,10,5,8]
Run Code Online (Sandbox Code Playgroud)
输出
[3,7,15,16]
Run Code Online (Sandbox Code Playgroud)
如您所见,一个有 6 个位置,另一个有 4 个。
那么如果它们重复,它们应该存储在另一个 ArrayList 中
我携带的代码:
import java.util.ArrayList;
public class inexistentes {
public static ArrayList<Integer> inexistentes(ArrayList<Integer> cd1, ArrayList<Integer> cd2){
ArrayList<Integer> newList = new ArrayList<>();
for(int i = 0; i < cd1.size(); i++){
if(cd1.contains(i) ){
newList.add(i);
}
}
return newList;
}
}
Run Code Online (Sandbox Code Playgroud)
我怎么能买到那些链子...
我已经有一个 for 但我不知道如何实现 if。
您不需要应用复杂的逻辑。使用该List#removeAll功能可以轻松满足您的要求。
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> cd1 = List.of(3, 5, 7, 10, 15, 16);
List<Integer> cd2 = List.of(4, 10, 5, 8);
List<Integer> result = new ArrayList<Integer>(cd1);
result.removeAll(cd2);
System.out.println(result);
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
[3, 7, 15, 16]
Run Code Online (Sandbox Code Playgroud)
但是,如果您仍然想按照自己的方式进行操作,请按以下步骤操作:
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> cd1 = List.of(3, 5, 7, 10, 15, 16);
List<Integer> cd2 = List.of(4, 10, 5, 8);
System.out.println(inexistentes(cd1, cd2));
}
public static ArrayList<Integer> inexistentes(List<Integer> cd1, List<Integer> cd2) {
ArrayList<Integer> newList = new ArrayList<>();
for (int i = 0; i < cd1.size(); i++) {
int n = cd1.get(i);
if (!cd2.contains(n)) {
newList.add(n);
}
}
return newList;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
73 次 |
| 最近记录: |