用Java连接数组?

时间:2014-10-31 00:58:03

标签: java arrays concatenation indexoutofboundsexception

我正在尝试编写一个接收两个数组并连接它们的方法。现在我收到错误“线程中的异常”主“java.lang.ArrayIndexOutOfBoundsException:2。”我不明白为什么会这样。有人可以解释为什么我收到此错误?

public static int [ ] concat (int [ ] nums1, int [ ] nums2)

    {
        int length = nums1.length+nums2.length;
        int nums3 [] = new int [length];
        for (int i=0; i<nums1.length; i++)
        {
            int value = nums1 [i];
            nums3 [i]=value;
        }
        for (int i=0; i<(nums1.length+nums2.length); i++)
        {
            int value=nums2 [i]; //It says I have an error on this line but I do not understand why.
         length = nums1.length+1;
            nums3 [length]= value;
        }
        return nums3;

    }

3 个答案:

答案 0 :(得分:1)

当您希望第二个循环仅跨越nums2的长度时,您的第二个循环将跨越连接长度。

试试这个:

    for (int i=nums1.length; i<nums2.length; i++)
    {
        int value=nums2 [i - num1.length];
        nums3 [i]= value;
    }

答案 1 :(得分:1)

使用Apache Commons Lang库。

String[] concat = ArrayUtils.addAll(nums1, nums2);

API

答案 2 :(得分:0)

这是一个有效的例子:

import java.util.Arrays;

public class test{
        public static int [] concat (int [] nums1, int [] nums2)
        {
                int length = nums1.length+nums2.length;
                int nums3 [] = new int [length];
                for (int i=0; i<nums1.length; i++)
                {
                        nums3[i] = nums1[i];
                }
                // You can start adding to nums3 where you had finished adding
                // in the previous loop. 
                for (int i=nums1.length; i< nums3.length; i++)
                {
                        // (i - nums1.length) will give you zero initially and 
                        // ends with nums2.length by the time this loop finishes
                        nums3[i]= nums2[i - nums1.length];
                }
                return nums3;

        }

        public static void main(String[] args) {

                int[] temp = {1,2,3,4};
                int[] temp2 = {1,2,3,4};
                System.out.println(Arrays.toString(concat(temp,temp2)));


        }

}

您还可以使用addAll中的方法ArrayUtils将这些方法添加到此线程Arrayutils thread中,但如果您想明确写出方法,那么这应该可行。