java将两个数组中不同的数字去掉一个剩下的保存到一个新的数组中
package co;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/**
* java将两个数组中不同的数字去掉一个剩下的保存到一个新的数组中
* @author jsb
*
*/
public abstract class test1 {
public static void main(String[] args) {
int[] n = new int[10];
int[] m = new int[10];
Set<Integer> set = new HashSet<Integer>();
for(int i=0;i<n.length;i++){
n[i] = (int)(Math.random()*10);
m[i] = (int)(Math.random()*10);
}
System.out.println(Arrays.toString(n));
System.out.println(Arrays.toString(m));
for(int i=0;i<10;i++){
for(int j=0;j<10;j++){
if(n[i]==m[j]){
int num = n[i];
set.add(num);
}
}
}
System.out.println(set);
}
}
结果:
[3, 0, 5, 8, 1, 7, 2, 8, 3, 1]
[4, 6, 2, 8, 6, 5, 0, 7, 0, 0]
[0, 2, 5, 7, 8]
public class Demo {
public static void main(String[] args) {
int[] a = { 1, 2, 3, 4 };
int[] b = { 3, 4, 5, 6, 7 };
int[] c = new int[a.length + b.length];
int count = 0;
int flag ;
for (int i = 0; i < a.length; i++) {
flag = 0;
for (int j = 0; j < b.length; j++) {
if (a[i] == b[j]) {
flag = 1;
break;
}
}
if (flag != 1) {
c[count] = a[i];
count++;
}
}
for (int i = 0; i < b.length; i++) {
flag = 0;
for (int j = 0; j < a.length; j++) {
if (b[i] == a[j]) {
flag = 1;
break;
}
}
if (flag != 1) {
c[count] = b[i];
count++;
}
}
for (int i = 0; i < count; i++)
System.out.print(c[i] + " ");
}
}