Java์ Arrays.copyOf() ๋ฉ์๋๋ ๋ฌด์์ ๋๊น?
Java ํด๋์ค java.util.Arrays๋ ์ด ํจ์์ ๋งค๊ฐ๋ณ์๋ก ์ ๋ฌ๋ ๋ฐฐ์ด์ ๋ณต์ฌ๋ณธ์ ๋ฐํํ๊ณ ํฌ๊ธฐ๋ฅผ ์ง์ ํ๋ Arrays.copyOf() ๋ผ๋ ๋ฉ์๋๋ฅผ ์ ๊ณตํฉ๋๋ค . ๋ค์์ ๋น ๋ฅธ ์ดํด๋ฅผ ์ํ ๋ฉ์๋ ํค๋์ ๋๋ค.
Arrays.copyOf(int[] templateArray, int length);
๋ ๋ฒ์งธ ๋งค๊ฐ๋ณ์ "๊ธธ์ด"๋ ์์ฑํ๋ ค๋ ๋ณต์ฌ ๋ฐฐ์ด์ ํฌ๊ธฐ์
๋๋ค. ๊ทธ๋์ ์ฌ๊ธฐ์ ์ฐ๋ฆฌ๋ 3๊ฐ์ง ๊ฒฝ์ฐ๋ฅผ ๊ฐ์ง ์ ์์ต๋๋ค.
- ํ ํ๋ฆฟ ๋ฐ ์ฌ๋ณธ ๋ฐฐ์ด์ ๊ธธ์ด๋ ๋์ผํฉ๋๋ค.
- ๋ณต์ฌ ๋ฐฐ์ด์ ๊ธธ์ด๊ฐ ํ ํ๋ฆฟ ๋ฐฐ์ด์ ๊ธธ์ด๋ณด๋ค ํฝ๋๋ค.
- ๋ณต์ฌ ๋ฐฐ์ด์ ๊ธธ์ด๋ ํ ํ๋ฆฟ ๋ฐฐ์ด์ ๊ธธ์ด๋ณด๋ค ์์ต๋๋ค.
![Java์ Arrays.copyOf() ๋ฉ์๋ - 1](https://cdn.codegym.cc/images/article/7aaa640a-f0f2-44f8-addd-39f0812569c2/800.jpeg)
์ฝ๋ฉ ์
import java.util.Arrays;
public class ArraysCopyOfMethod {
public static void main(String[] args) {
// Initialize your templateArray which you want a copy of
int[] templateArray = new int[] {1, 2, 3, 4, 5, 6};
System.out.println("Template Array: " + Arrays.toString(templateArray));
// Create a "copy" of template array using
// Arrays.copyOf(int[] array, int arrayLength) method
// CASE 1: Sizes of both template & copy arrays are same
int[] copyArray1 = Arrays.copyOf(templateArray, templateArray.length);
System.out.println("Copy Array 1: " + Arrays.toString(copyArray1));
// CASE 2: Size of copy array > Size of template array
// extra space in copy array is filled with zeros
int[] copyArray2 = Arrays.copyOf(templateArray, 10);
System.out.println("Copy Array 2: " + Arrays.toString(copyArray2));
// CASE 3: Size of copy array < Size of template array
// copy array is only filled with only elements in overlapping size
int[] copyArray3 = Arrays.copyOf(templateArray, 3);
System.out.println("Copy Array 3: " + Arrays.toString(copyArray3));
}
}
์ฐ์ถ
ํ
ํ๋ฆฟ ๋ฐฐ์ด: [1, 2, 3, 4, 5, 6] ๋ฐฐ์ด 1 ๋ณต์ฌ: [1, 2, 3, 4, 5, 6] ๋ฐฐ์ด 2 ๋ณต์ฌ: [1, 2, 3, 4, 5, 6, 0, 0, 0, 0] ์ด๋ ์ด 3 ๋ณต์ฌ: [1, 2, 3]
GO TO FULL VERSION