import java.util.ArrayList;
public class ArrayOperation {
public static int[] arraySubtract(int[] array1, int[] array2) {
ArrayList<Integer> list = new ArrayList<Integer>();
//选出属于数组1但不属于数组2的元素
for(int i = 0; i < array1.length; ++i) {
boolean bContained = false;
for(int j = 0; j < array2.length; ++j) {
if (array1[i] == array2[j]) {
bContained = true;
break;
}
}
if (!bContained) {
list.add(array1[i]);
}
}
int res[] = new int[list.size()];
for(int i = 0; i < list.size(); ++i)
res[i] = list.get(i);
return res;
}
public static void main(String args[]) {
int[] array1 = new int[]{1, 2, 3, 4, 5, 6, 7};
int[] array2 = new int[]{2, 4, 6};
//计算两个数组的差
int[] res = arraySubtract(array1, array2);
//打印结果
for(int i = 0; i < res.length; ++i) {
System.out.print(res[i] +" ");
}
System.out.println();
}
}
运行效果截图:
![](https://video.ask-data.xyz/img.php?b=https://iknow-pic.cdn.bcebos.com/b21bb051f81986187afb65534bed2e738ad4e6ad?x-bce-process=image%2Fresize%2Cm_lfit%2Cw_600%2Ch_800%2Climit_1%2Fquality%2Cq_85%2Fformat%2Cf_auto)