比较两个数组中相同元素并打印出来

来源:互联网 发布:网络教育有学位证书吗 编辑:程序博客网 时间:2024/06/11 07:49

这个方法比较笨,但是里面也有一点可以学习的东西。Arrays.asList的用法没那么简单。

//找出链各个数组中相同的元素import java.util.*;class SelectSame{public static void main(String[] args) {int[] a={1,2,3,6,89,32,7};int[] b={0,65,7,34,6,76,31,54,70,12};int[] w=select1(a,b); System.out.println("相同元素为:");for (int i=0;i<w.length ;i++ ){if (w[i]!=0){ System.out.println(w[i]);}}}public static int[] select1(int[] a,int[] b){int[] m=a.length>b.length?a:b;//获取两个数组中元素个数比较多的那个数组int[] n=a.length<b.length?a:b;//获取两个数组中元素个数比较少的那个数组String[] strs=new String[m.length];for (int i=0;i<m.length ;i++ ){strs[i]=m[i]+"";}ArrayList al1=new ArrayList(Arrays.asList(strs));int[] c=new int[n.length];int j=0;System.out.println(n.length);for (int i=n.length-1;i>=0 ;i-- ){System.out.print("n[i]--"+n[i]);if (al1.contains(n[i]+"")){c[j++]=n[i];}}return c;}}


0 0
原创粉丝点击