對於兩個數組
arr1=[1,3,4,5,8,9]
arr2=[2,3,7,8,9]
求出交集與並集
test.java
1 import java.util.ArrayList; 2 import java.util.Collections; 3 4 5 public class test1 { 6 public static void main(String[] args) { 7 ArrayList<Integer> tmplist=new ArrayList<Integer>(); 8 int[] arr1={1,3,4,5,8,9}; 9 int[] arr2={2,3,7,8,9}; 10 tmplist=Intersection(arr1,arr2); 11 OutPut(tmplist); 12 tmplist.clear(); 13 tmplist=Union(arr1,arr2); 14 OutPut(tmplist); 15 } 16 private static ArrayList<Integer> Intersection(int[] a1,int[] a2){ 17 ArrayList<Integer> list=new ArrayList<Integer>(); 18 for(int i=0;i<a1.length;i++) 19 for(int j=0;j<a2.length;j++) 20 if(a1[i]==a2[j]) 21 list.add(a2[j]); 22 return list; 23 } 24 25 private static ArrayList<Integer> Union(int[] a1,int[] a2){ 26 ArrayList<Integer> list1=new ArrayList<Integer>(); 27 ArrayList<Integer> list2=new ArrayList<Integer>(); 28 for(int i:a1) 29 list1.add(i); 30 for(int i:a2) 31 list2.add(i); 32 list1.removeAll(list2); 33 list2.addAll(list1); 34 return list2; 35 } 36 37 private static void OutPut(ArrayList<Integer> list){ 38 Collections.sort(list); 39 if(list.size()==0) 40 System.out.println("null"); 41 else 42 for(int i:list) 43 System.out.print(i); 44 System.out.println("\n"); 45 } 46 }