對於兩個數組
arr1=[1,3,4,5,8,9]
arr2=[2,3,7,8,9]
求出交集與並集
test.java
import java.util.ArrayList; import java.util.Collections; public class test1 { public static void main(String[] args) { ArrayList<Integer> tmplist=new ArrayList<Integer>(); int[] arr1={1,3,4,5,8,9}; int[] arr2={2,3,7,8,9}; tmplist=Intersection(arr1,arr2); OutPut(tmplist); tmplist.clear(); tmplist=Union(arr1,arr2); OutPut(tmplist); } private static ArrayList<Integer> Intersection(int[] a1,int[] a2){ ArrayList<Integer> list=new ArrayList<Integer>(); for(int i=0;i<a1.length;i++) for(int j=0;j<a2.length;j++) if(a1[i]==a2[j]) list.add(a2[j]); return list; } private static ArrayList<Integer> Union(int[] a1,int[] a2){ ArrayList<Integer> list1=new ArrayList<Integer>(); ArrayList<Integer> list2=new ArrayList<Integer>(); for(int i:a1) list1.add(i); for(int i:a2) list2.add(i); list1.removeAll(list2); list2.addAll(list1); return list2; } private static void OutPut(ArrayList<Integer> list){ Collections.sort(list); if(list.size()==0) System.out.println("null"); else for(int i:list) System.out.print(i); System.out.println("\n"); } }