1

If I have two arrays.

int[] one; int[] two;

And I want to add both the arrays into a single array in easiest way that means
` int[] combine=// what can I do here?

mhall
  • 3,671
  • 3
  • 23
  • 35

8 Answers8

3
int [][] A={{1,2,4},{2,4,5},{2,4,4}};   
int [][] B={{3,5,4},{0,1,9},{6,1,3}};   
int i,j;
int [][] C=new int[3][3];
int X=A.length;
for(i=0; i<X; i++)
{for(j=0; i<X; i++)
    {
    C[i][j]=A[i][j]+B[i][j];
       }
}
for(i=0; i<X; i++)
{
    for(j=0; j<X; j++){
        System.out.print(C[i][j]+"   ");
    }
    System.out.println();

    }   
Ali Wahiib
  • 31
  • 1
2

Use of ArrayUtils from Apache Commons Lang library:

int[] combine = ArrayUtils.addAll(one, two);

http://commons.apache.org/lang/api-2.5/org/apache/commons/lang/ArrayUtils.html#addAll(int[], int[])

Nathan Q
  • 1,892
  • 17
  • 40
2

Use ArrayUtils class Method addAll which Adds all the elements of the given arrays into a new array.The new array contains all of the element of array1 followed by all of the elements array2. When an array is returned, it is always a new array.

ArrayUtils.addAll(array1,array2);   

Returns: The new int[] array

Community
  • 1
  • 1
1

Try this:

int [][] A={{1,2,4},{2,4,5},{2,4,4}};   
int [][] B={{3,5,4},{0,1,9},{6,1,3}};   
int i,j;
int [][] C=new int[3][3];
int X=A.length;
int y=B.length;
for(i=0; i<X; i++)
{
    for(j=0; i<Y; i++)
    {
        C[i][j]=A[i][j]+B[i][j];
    }
}
for(i=0; i<X; i++)
{
    for(j=0; j<X; j++)
    {
        System.out.print(C[i][j]+"   ");
    }
    System.out.println();
}   
Patrick Kostjens
  • 5,065
  • 6
  • 29
  • 46
HAYAH
  • 11
  • 1
1
int[] one = new int[]{1, 2, 3, 4, 5};
int[] two = new int[]{3, 7, 8, 9};
int[] result = new int[one.length + two.length];
System.arraycopy(one, 0, result, 0, one.length);
System.arraycopy(two, 0, result, one.length, two.length);
System.out.println("Arrays.toString(result) = " + Arrays.toString(result));
Boris Pavlović
  • 63,078
  • 28
  • 122
  • 148
0

try this:

int size1 = one.length;
int size2 = two.length;
int[] three = new int[size1 + size2];

for(int i = 0; i < one.length; i++)
     three[i] = one[i];

for(int i = two.length; i < one.length + two.length; i++)
     three[i] = one[i];
Thomas Uhrig
  • 30,811
  • 12
  • 60
  • 80
0
int[] combined = new int[one.length()+two.length()];
for(int i=0; i<one.length(); ++i){
combined[i] = one[i];}

for(int i=one.length(); i<combined.length(); ++i){
 combined[i] = two[i-one.length()];
}

Code not tested. Note that you could make some optimizations by unwrapping the length() methods.

poitroae
  • 21,129
  • 10
  • 63
  • 81
-1
int[] combinedArrays = new int[one.length + two.length];
int index = 0;
for (int i : one) {
    combinedArarys[index] = one[i];
    index++;
}

for (int i : two) {
    two[index] = two[i];
    index++;
}
LuckyLuke
  • 47,771
  • 85
  • 270
  • 434