Arrays.copyOf

이규현·2024년 8월 14일

배열을 이용한 자료구조 공부 중 Arrays.copyOf 기능을 알게 되었다.

//배열을 새로 만들고, 기존 배열을 새로운 배열에 복사
int oldCapacity = elementData.length;
int newCapacity = oldCapacity*2;
Object[] newArr = new Object[newCapacity];
for(int i=0; i<elementData.length;i++){
     newArr[i]= elementData[i];
}
elementData= newArr;

배열의 크기를 키워주는 grow() 메소드를 사용할 때 새로운 배열에 기존 배열을 복사해서 넣어주는데 위와 같은 코드를 사용했다.

elementData = Arrays.copyOf(elementData, newCapacity);

Arrays.copyOf 를 통해 복잡한 코드를 간결하게 바꿀 수 있다.
기능만을 생각해볼 수 있지만 위와 같이 비교 코드를 통해 이해했다.

0개의 댓글