2011-11-16 5 views
1

두 개의 배열이있는 경우.나는 2 개의 어레이를 가지고 있는데, 하나의 어레이에 2 개의 어레이를 추가하고 싶습니다.하지만 어떻게 ..?

int[] one; int[] two;

그리고
가`[] 내가 여기서 무엇을 = 할 수 // 결합하는 int 즉, 가장 쉬운 방법에서 단일 배열 로 배열을 모두 추가 할? 아파치 코 몬즈 랭 라이브러리에서 ArrayUtils의

+1

가능한 중복 : http://stackoverflow.com/questions/80476/how-to -concatenate-two-arrays-in-java – Dennis

+0

이 링크를 통해 가십시오 http://stackoverflow.com/questions/80476/how-to-concatenate-two-arrays-in-java –

답변

1

이이 작업을 수행하는 하나 개의 옵션 ... 새로운 array.The 새로운 배열로 주어진 배열의 모든 요소를 ​​추가

int[] combine= new T[one.length+two.length]; 
System.arraycopy(one, 0, combine, 0, one.length); 
System.arraycopy(two, 0, combine, one.length, two.length); 
0

이 시도 :

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]; 
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)); 
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()]; 
} 

코드하지 테스트. length() 메서드의 래핑을 해제하여 최적화를 수행 할 수 있습니다.

-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++; 
} 
2

사용 ArrayUtilsclass 방법 addAll이 모두 포함입니다 array1의 요소 다음에 모든 요소 array2가옵니다. 배열이 반환되면 항상 새로운 배열입니다.

ArrayUtils.addAll(array1,array2); 

반환 값 : 새로운 int[] array

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(); 

    } 
1

이 시도 :

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(); 
} 
관련 문제