logo

Java의 동적 배열

배열은 크기가 고정되어 있고 동질적입니다. 데이터 구조 . 배열의 한계는 크기가 고정되어 있다는 것입니다. 이는 배열을 선언할 때 요소 수를 지정해야 함을 의미합니다. 여기서 질문이 생깁니다. 요소를 삽입하려고 하는데 새 요소를 위한 공간이 더 이상 남아 있지 않다면 어떻게 해야 할까요? 여기서의 개념은 동적 배열 존재하게 된다. 배열의 크기를 동적으로 확장합니다.

이 섹션에서 우리는 이해할 것입니다 동적 배열이란 무엇입니까, 동적 배열의 기능, 동적 배열 크기를 조정하는 방법, 그리고 Java에서 동적 배열을 구현하는 방법 .

움직이는 HTML

동적 배열이란 무엇입니까?

동적 배열은 가변 크기 목록 데이터 구조. 새 요소를 위한 공간이 더 이상 남아 있지 않으면 요소를 삽입하려고 할 때 자동으로 커집니다. 이를 통해 요소를 추가하고 제거할 수 있습니다. 힙을 사용하여 런타임에 메모리를 할당합니다. 런타임 중에 크기를 변경할 수 있습니다.

~ 안에 자바 , 배열목록 크기 조정이 가능한 구현입니다. List 인터페이스를 구현하고 목록 작업과 관련된 모든 메서드를 제공합니다. 동적 배열의 장점은 다음과 같습니다.

  • 빠른 조회
  • 가변 크기
  • 캐시 친화적

동적 배열 작업

동적 배열에서는 요소가 배열 시작부터 연속적으로 저장되고 나머지 공간은 사용되지 않은 상태로 유지됩니다. 예약된 공간이 완전히 소모될 때까지 요소를 추가할 수 있습니다. 예약된 공간이 소비되어 일부 요소를 추가해야 하는 경우. 이러한 경우 고정 크기 배열의 크기를 늘려야 합니다. 요소를 추가하기 전에 더 큰 배열을 할당하고 배열에서 요소를 복사한 다음 새로 생성된 배열을 반환합니다.

자바 메인

요소를 추가하는 또 다른 방법은 먼저 두 배 크기의 새 배열을 만들고 이전 배열의 모든 요소를 ​​복사한 다음 새 배열을 반환하는 함수를 만드는 것입니다. 마찬가지로 동적 배열의 크기를 줄일 수도 있습니다.

크기와 용량

동적 배열을 초기화하면 고정 크기 배열이 생성됩니다. 다음 그림에서 배열 구현에는 10개의 인덱스가 있습니다. 배열에 5개의 요소를 추가했습니다. 이제 기본 배열의 길이는 5입니다. 따라서 동적 배열 크기의 길이는 5이고 용량은 10입니다. 동적 배열은 끝점을 추적합니다.

Java의 동적 배열

동적 배열의 특징

Java에서 동적 배열에는 세 가지 주요 기능이 있습니다. 요소를 추가하고, 요소를 삭제하고, 배열의 크기를 조정합니다.

동적 배열에 요소 추가

동적 배열에서는 배열에 요소를 더 추가해야 하는 경우 고정 크기 배열을 만들 수 있습니다. 일반적으로 두 배 크기의 새 배열을 만듭니다. 그런 다음 모든 요소를 ​​새로 생성된 배열에 복사합니다. 우리는 다음 접근 방식을 사용합니다.

자바의 추상 클래스
Java의 동적 배열

동적 배열에서 요소 삭제

배열의 지정된 인덱스에 있는 요소를 제거하려면 다음을 사용합니다. 제거 위치(i) 방법. 이 메소드는 삭제하려는 요소의 색인 번호를 구문 분석합니다. 요소를 삭제한 후, 지정된 인덱스 번호에서 나머지 요소(삭제된 요소의 오른쪽에 있는 요소)를 왼쪽으로 이동합니다. 또한 배열 끝에서 요소를 삭제하는 Remove() 메서드를 사용합니다. 요소를 이동한 후 저장합니다. 0 마지막 요소의 궁전에서. 다음 그림과 같이 예를 통해 이해해 보겠습니다.

Java의 동적 배열

Java에서 동적 배열 크기 조정

다음과 같은 경우 두 가지 시나리오에서 배열 크기를 조정해야 합니다.

  • 어레이는 필요한 것보다 추가 메모리를 사용합니다.
  • 배열은 모든 메모리를 차지하므로 요소를 추가해야 합니다.

첫 번째 경우에는 다음을 사용합니다. 싱크사이즈() 크기를 조정하는 방법 정렬 . 배열의 크기를 줄입니다. 추가 또는 사용되지 않은 메모리를 확보합니다. 두 번째 경우에는 다음을 사용합니다. 성장크기() 배열의 크기를 조정하는 방법. 배열의 크기가 늘어납니다.

더 큰 배열이 필요하고 이전 배열의 모든 요소를 ​​복사한 후 새 배열을 반환하기 때문에 비용이 많이 드는 작업입니다.

Java의 동적 배열

위의 배열에서 6개의 요소를 더 추가해야 하고 배열에 요소를 저장할 메모리가 더 이상 남아 있지 않다고 가정합니다. 그러한 경우에는 다음을 사용하여 배열을 확장합니다. 성장크기() 방법.

문자열을 int로 변환하는 방법 java
Java의 동적 배열

동적 배열 초기화

동적 배열의 초기화는 정적 배열과 동일합니다. 동적 배열을 초기화하는 다음 Java 프로그램을 고려하십시오.

초기화DynamicArray.java

 public class InitializeDynamicArray { public static void main(String[] args) { //declaring array int array[]; //initialize an array array= new int[6]; //adding elements to the array array[0] = 34; array[1] = 90; array[2] = 12; array[3] = 22; array[4] = 9; array[5] = 27; System.out.print(&apos;Elements of Array are: &apos;); //iteraton over the array for(int i=0; i <array.length ; i++) { system.out.print(array[i] +' '); } < pre> <p> <strong>Output:</strong> </p> <pre> Elements of Array are: 34 90 12 22 9 27 </pre> <p>Let&apos;s implement the operations in a Java program that we have discussed above.</p> <p> <strong>DynamicArrayExample1.java</strong> </p> <pre> public class DynamicArrayExample1 { private int array[]; private int count; private int sizeofarray; //creating a constructor of the class that initializes the values public DynamicArrayExample1() { array = new int[1]; count = 0; sizeofarray = 1; } //creating a function that appends an element at the end of the array public void addElement(int a) { //compares if the number of elements is equal to the size of the array or not if (count == sizeofarray) { //invoking the growSize() method that creates an array of double size growSize(); } //appens an element at the end of the array array[count] = a; count++; } //function that creates an array of double size public void growSize() { //declares a temp[] array int temp[] = null; if (count == sizeofarray) { //initialize a double size array of array temp = new int[sizeofarray * 2]; { for (int i = 0; i <sizeofarray; i++) { copies all the elements of old array temp[i]="array[i];" } sizeofarray="sizeofarray" * 2; creating a function that deletes an element at specified index public void addelementat(int index, int a) compare size with number if not equal grows (count="=" sizeofarray) invoking growsize() method growsize(); for (int i="count" - 1;>= index; i--) { //shifting all the elements to the left from the specified index array[i + 1] = array[i]; } //inserts an element at the specified index array[index] = a; count++; } public static void main(String[] args) { DynamicArrayExample1 da = new DynamicArrayExample1(); //adding elements to the array da.addElement(12); da.addElement(22); da.addElement(35); da.addElement(47); da.addElement(85); da.addElement(26); da.addElement(70); da.addElement(81); da.addElement(96); da.addElement(54); System.out.println(&apos;Elements of the array:&apos;); //iterate over the array for accessing the elements for (int i = 0; i <da.sizeofarray; 5 99 i++) { system.out.print(da.array[i] + ' '); } system.out.println(); determines and prints the size number of elements array system.out.println('size array: da.sizeofarray); system.out.println('no. in da.count); invoking method to add an element at specified index da.addelementat(5, 99); where is be system.out.println('
elements after adding 5:'); iterate over for accessing (int i="0;" < da.sizeofarray; pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/java-tutorial/02/dynamic-array-java-6.webp" alt="Dynamic Array in Java"> <p>Let&apos;s shrink the array, delete the last element, and a specified element from the array.</p> <p> <strong>DynamicArrayExample2.java</strong> </p> <pre> public class DynamicArrayExample2 { private int array[]; private int count; private int sizeofarray; //creating a constructor of the class that initializes the values public DynamicArrayExample2() { array = new int[1]; count = 0; sizeofarray = 1; } //creating a function that appends an element at the end of the array public void addElement(int a) { //compares if the number of elements is equal to the size of the array or not if (count == sizeofarray) { //invoking the growSize() method that creates an array of double size growSize(); } //appens an element at the end of the array array[count] = a; count++; } //function that creates an array of double size public void growSize() { //declares a temp[] array int temp[] = null; if (count == sizeofarray) { //initialize a double size array of array temp = new int[sizeofarray * 2]; { for (int i = 0; i <sizeofarray; i++) { copies all the elements of old array temp[i]="array[i];" } sizeofarray="sizeofarray" * 2; method removes unused space public void shrinksize() declares a temp[] int if (count> 0) { //creates an array of the size equal to the count i.e. number of elements the array have temp = new int[count]; for (int i = 0; i <count; i++) { copies all the elements of old array temp[i]="array[i];" } sizeofarray="count;" creating a function that removes last for public void removeelement() if (count> 0) { array[count - 1] = 0; count--; } } //creating a function that delets an element from the specified index public void removeElementAt(int index) { if (count &gt; 0) { for (int i = index; i <count 7 - 1; i++) { shifting all the elements to left from specified index array[i]="array[i" + 1]; } array[count 1]="0;" count--; public static void main(string[] args) dynamicarrayexample2 da="new" dynamicarrayexample2(); adding array da.addelement(12); da.addelement(22); da.addelement(35); da.addelement(47); da.addelement(85); da.addelement(26); da.addelement(70); da.addelement(81); da.addelement(96); da.addelement(54); system.out.println('elements of array:'); iterate over for accessing (int i="0;" < da.sizeofarray; system.out.print(da.array[i] ' '); system.out.println(); determines and prints size number system.out.println('size array: da.sizeofarray); system.out.println('no. in da.count); invoking method delete last element da.removeelement(); after deleting system.out.print('
elements element: system.out.print('no. da.count+'
'); that deletes an da.removeelementat(7); at 7: pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/java-tutorial/02/dynamic-array-java-7.webp" alt="Dynamic Array in Java"> <hr></count></count;></sizeofarray;></pre></da.sizeofarray;></sizeofarray;></pre></array.length>

위에서 논의한 Java 프로그램에서 작업을 구현해 보겠습니다.

DynamicArrayExample1.java

 public class DynamicArrayExample1 { private int array[]; private int count; private int sizeofarray; //creating a constructor of the class that initializes the values public DynamicArrayExample1() { array = new int[1]; count = 0; sizeofarray = 1; } //creating a function that appends an element at the end of the array public void addElement(int a) { //compares if the number of elements is equal to the size of the array or not if (count == sizeofarray) { //invoking the growSize() method that creates an array of double size growSize(); } //appens an element at the end of the array array[count] = a; count++; } //function that creates an array of double size public void growSize() { //declares a temp[] array int temp[] = null; if (count == sizeofarray) { //initialize a double size array of array temp = new int[sizeofarray * 2]; { for (int i = 0; i <sizeofarray; i++) { copies all the elements of old array temp[i]="array[i];" } sizeofarray="sizeofarray" * 2; creating a function that deletes an element at specified index public void addelementat(int index, int a) compare size with number if not equal grows (count="=" sizeofarray) invoking growsize() method growsize(); for (int i="count" - 1;>= index; i--) { //shifting all the elements to the left from the specified index array[i + 1] = array[i]; } //inserts an element at the specified index array[index] = a; count++; } public static void main(String[] args) { DynamicArrayExample1 da = new DynamicArrayExample1(); //adding elements to the array da.addElement(12); da.addElement(22); da.addElement(35); da.addElement(47); da.addElement(85); da.addElement(26); da.addElement(70); da.addElement(81); da.addElement(96); da.addElement(54); System.out.println(&apos;Elements of the array:&apos;); //iterate over the array for accessing the elements for (int i = 0; i <da.sizeofarray; 5 99 i++) { system.out.print(da.array[i] + \' \'); } system.out.println(); determines and prints the size number of elements array system.out.println(\'size array: da.sizeofarray); system.out.println(\'no. in da.count); invoking method to add an element at specified index da.addelementat(5, 99); where is be system.out.println(\'
elements after adding 5:\'); iterate over for accessing (int i="0;" < da.sizeofarray; pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/java-tutorial/02/dynamic-array-java-6.webp" alt="Dynamic Array in Java"> <p>Let&apos;s shrink the array, delete the last element, and a specified element from the array.</p> <p> <strong>DynamicArrayExample2.java</strong> </p> <pre> public class DynamicArrayExample2 { private int array[]; private int count; private int sizeofarray; //creating a constructor of the class that initializes the values public DynamicArrayExample2() { array = new int[1]; count = 0; sizeofarray = 1; } //creating a function that appends an element at the end of the array public void addElement(int a) { //compares if the number of elements is equal to the size of the array or not if (count == sizeofarray) { //invoking the growSize() method that creates an array of double size growSize(); } //appens an element at the end of the array array[count] = a; count++; } //function that creates an array of double size public void growSize() { //declares a temp[] array int temp[] = null; if (count == sizeofarray) { //initialize a double size array of array temp = new int[sizeofarray * 2]; { for (int i = 0; i <sizeofarray; i++) { copies all the elements of old array temp[i]="array[i];" } sizeofarray="sizeofarray" * 2; method removes unused space public void shrinksize() declares a temp[] int if (count> 0) { //creates an array of the size equal to the count i.e. number of elements the array have temp = new int[count]; for (int i = 0; i <count; i++) { copies all the elements of old array temp[i]="array[i];" } sizeofarray="count;" creating a function that removes last for public void removeelement() if (count> 0) { array[count - 1] = 0; count--; } } //creating a function that delets an element from the specified index public void removeElementAt(int index) { if (count &gt; 0) { for (int i = index; i <count 7 - 1; i++) { shifting all the elements to left from specified index array[i]="array[i" + 1]; } array[count 1]="0;" count--; public static void main(string[] args) dynamicarrayexample2 da="new" dynamicarrayexample2(); adding array da.addelement(12); da.addelement(22); da.addelement(35); da.addelement(47); da.addelement(85); da.addelement(26); da.addelement(70); da.addelement(81); da.addelement(96); da.addelement(54); system.out.println(\'elements of array:\'); iterate over for accessing (int i="0;" < da.sizeofarray; system.out.print(da.array[i] \' \'); system.out.println(); determines and prints size number system.out.println(\'size array: da.sizeofarray); system.out.println(\'no. in da.count); invoking method delete last element da.removeelement(); after deleting system.out.print(\'
elements element: system.out.print(\'no. da.count+\'
\'); that deletes an da.removeelementat(7); at 7: pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/java-tutorial/02/dynamic-array-java-7.webp" alt="Dynamic Array in Java"> <hr></count></count;></sizeofarray;></pre></da.sizeofarray;></sizeofarray;>