System.arraycopy() 메서드를 이용해서 배열의 값을 복사할 수 있다.
for문을 사용한 것보다 효율적이라는 장점이 있다.
사용법
System.arraycopy(from객체, 복사시작 index, to객체, to객체의 복사시작 index, 복사할 원소의 개수);
package test;
public class Test {
public static void main(String[] args) {
int[] fromArr = {10, 20, 30, 40, 50};
int[] toArr = new int[fromArr.length];
System.arraycopy(fromArr, 0, toArr, 0, fromArr.length);
int i = 0;
for(int a : toArr) {
System.out.println(i++ + "번째 원소 : " + a);
}
}
}
주의사항
to객체의 범위를 초과하여 데이터를 넣으려고 하면 ArrayIndexOutOFBoundsException오류가 발생한다.
'Java' 카테고리의 다른 글
메모리구조(stack, heap, method area) (0) | 2023.05.04 |
---|---|
가변배열, 가변인자 (0) | 2023.05.02 |
for each (0) | 2023.04.25 |
인코딩과 디코딩 (0) | 2023.04.21 |
scanner 사용법 (0) | 2023.04.18 |