日期:2014-05-20 浏览次数:20784 次
import java.util.*; class ShuZuDemo{ public static void main(String[] args){ String a[] = {"1","2","3","6","8","0"}; String b[] = {"3","4","5","8","9"}; List data1 = Arrays.asList(a); List data2 = Arrays.asList(b); List list1 = new ArrayList(); List list2 = new ArrayList(); List list3 = new ArrayList(); for(int i=0;i <a.length;i++) { if(data2.indexOf(a[i])!=-1)//表示a中的存在于b中 { list2.add(a[i]);//list2表示a中存在于b中的元素的集合 }else { list1.add(a[i]); } } for(int i=0;i <b.length;i++) { if(data1.indexOf(b[i])==-1) { list3.add(b[i]); } } System.out.print("在数组a中"); print(list2); System.out.println("存在于数组b中"); System.out.print("在数组a中"); print(list1); System.out.println("在于b数组中不存在"); System.out.print("在数组b中"); print(list3); System.out.println("在于a数组中不存在"); } public static void print(List list){ Iterator it=list.iterator(); while(it.hasNext()){ System.out.print(it.next()+","); } } }
------解决方案--------------------
public static void main(String[] args) { String[] a = { "1", "2", "3" }; String[] b = { "3", "4", "5" }; Set<String> s1 = new HashSet<String>(); for (String s : a) { s1.add(s); } Set<String> s2 = new HashSet<String>(); for (String s : b) { s2.add(s); } s1.removeAll(s2); // 去掉s1里面任何s2包含的东西 for(String s : s1) { System.out.println(s); } }
------解决方案--------------------
import java.util.Arrays; import java.util.List; /* * @功能描述:判断是否存在,分别遍历两个数组,如果存在,打印出来 * @author sundful * */ public class ArrayTest { public static void main(String[] args) { String[] a={"1","2","3"}; String[] b={"3","4","5"}; List list1=Arrays.asList(a); List list2=Arrays.asList(b); for(Object s : list1) { if(list2.indexOf(s)!=-1) { System.out.println(s+"存在于数组b中"); }else{ System.out.println(s+"不存在于数组b中"); } } for(Object s : list2) { if(list1.indexOf(s)!=-1) { System.out.println(s+"存在于数组a中"); }else{ System.out.println(s+"不存在于数组a中"); } } } }