黑马程序员技术交流社区

标题: 数组的合并 [打印本页]

作者: 李晓泉    时间: 2013-3-14 09:45
标题: 数组的合并
怎样将两个一维数组合并成一个一维数组?
作者: 马甲大王    时间: 2013-3-14 10:10
如果两个数组的类型一样,就再定义一个空间是这两个数组空间和的数组然后
  1. String[] str1 = new String[]{"你好","黑马"};
  2.         String[] str2 = new String[]{"谢谢"};
  3.         
  4.         String[] str3 = new String [str1.length+str2.length];
  5.         System.arraycopy(str1, 0, str3, 0, str1.length);
  6.         System.arraycopy(str2, 0, str3, str1.length, str2.length);
  7.         for(String str:str3){
  8.                 System.out.print(str+",");
  9.         }
复制代码

作者: 李准    时间: 2013-3-14 10:14

            //       1、两个ArrayList集合{"a","b","c","d","e"}   {"d","e","f","g","h"},将这个两个集合去除重复项并合并成一个。
            ArrayList arrayOne = new ArrayList() { "a", "b", "c", "d", "e" };
            ArrayList arrayTwo = new ArrayList() { "d", "e", "f", "g", "h" };
            ArrayList arrayThree = new ArrayList();//新集合

            arrayThree.AddRange(arrayOne);//新集合中加入第一个集合
            for (int i = 0; i < arrayTwo.Count; i++)
            {
                //判断如果新集合中不包含第二个集合中的数
                if (!arrayThree.Contains(arrayTwo[i]))
                {
                    arrayThree.Add(arrayTwo[i]);
                }
            }

            //遍历输出新集合
            for (int i = 0; i < arrayThree.Count; i++)
            {
                Console.WriteLine(arrayThree[i]);
            }

            Console.ReadKey();
希望可以帮到你!
作者: jdzzlf    时间: 2013-3-14 10:25
采用集合数组,将这两个数组的值,都加入到一个集合数组中如ArrayList,然后,在将ArrayList中的值,赋值给第三个数组。例如:
        int a[]={1,2,3};
        int b[]={4,5,6};
               
        ArrayList<Integer> list=new ArrayList<Integer>(a.length+b.length);
                       
        for (int j = 0; j < a.length; j++)
        {
                list.add(a[j]);
        }
        for (int k = 0; k < b.length; k++)
        {
                list.add(b[k]);
        }
        int c[] =new int[list.size()];
        for(int i=0; i<list.size();i++)
        {
                c[i]=list.get(i);
        }
作者: 石国庆    时间: 2013-3-14 15:50
系统函数还真是厉害,我是新手,好多都不了解,1楼的方法学习了




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2