logo

Dynamisches Array in Java

Ein Array hat eine feste Größe und ist homogen Datenstruktur . Die Einschränkung von Arrays besteht darin, dass sie eine feste Größe haben. Das bedeutet, dass wir bei der Deklaration des Arrays die Anzahl der Elemente angeben müssen. Hier stellt sich die Frage: Was ist, wenn wir ein Element einfügen möchten und kein Platz mehr für das neue Element vorhanden ist? Hier ist das Konzept von dynamisches Array entsteht. Es erweitert die Größe des Arrays dynamisch.

Java-Tutorials

In diesem Abschnitt werden wir es verstehen Was ist ein dynamisches Array, welche Funktionen hat das dynamische Array, wie ändert man die Größe eines dynamischen Arrays? Und wie man ein dynamisches Array in Java implementiert .

Was ist ein dynamisches Array?

Das dynamische Array ist ein variable Größe Listendatenstruktur. Es wächst automatisch, wenn wir versuchen, ein Element einzufügen, wenn kein Platz mehr für das neue Element vorhanden ist. Es ermöglicht uns, Elemente hinzuzufügen und zu entfernen. Es reserviert zur Laufzeit Speicher mithilfe des Heaps. Es kann seine Größe während der Laufzeit ändern.

In Java , Anordnungsliste ist eine in der Größe veränderbare Implementierung. Es implementiert die List-Schnittstelle und stellt alle Methoden im Zusammenhang mit den Listenoperationen bereit. Die Stärke des dynamischen Arrays ist:

  • Schnelle Suche
  • Variable Größe
  • Cache-freundlich

Funktionsweise von Dynamic Array

Im dynamischen Array werden die Elemente vom Anfang des Arrays an zusammenhängend gespeichert und der verbleibende Platz bleibt ungenutzt. Wir können die Elemente hinzufügen, bis der reservierte Abstand vollständig verbraucht ist. Wenn der reservierte Speicherplatz verbraucht ist und einige Elemente hinzugefügt werden müssen. In einem solchen Fall muss das Array mit fester Größe vergrößert werden. Beachten Sie, dass wir vor dem Anhängen des Elements ein größeres Array zuweisen, die Elemente aus dem Array kopieren und das neu erstellte Array zurückgeben.

Eine andere Möglichkeit, ein Element hinzuzufügen, besteht darin, zunächst eine Funktion zu erstellen, die ein neues Array doppelter Größe erstellt, alle Elemente aus dem alten Array kopiert und das neue Array zurückgibt. Ebenso können wir auch die Größe des dynamischen Arrays verkleinern.

Größe vs. Kapazität

Durch die Initialisierung eines dynamischen Arrays wird ein Array mit fester Größe erstellt. In der folgenden Abbildung verfügt die Array-Implementierung über 10 Indizes. Wir haben dem Array fünf Elemente hinzugefügt. Das zugrunde liegende Array hat nun eine Länge von fünf. Daher beträgt die Länge des dynamischen Arrays 5 und seine Kapazität 10. Das dynamische Array verfolgt den Endpunkt.

Fibonacci-Folge Java
Dynamisches Array in Java

Merkmale des dynamischen Arrays

In Java verfügt das dynamische Array über drei Hauptfunktionen: Fügen Sie ein Element hinzu, löschen Sie ein Element und ändern Sie die Größe eines Arrays.

Element in einem dynamischen Array hinzufügen

Im dynamischen Array können wir ein Array mit fester Größe erstellen, wenn wir dem Array weitere Elemente hinzufügen möchten. Normalerweise wird ein neues Array mit doppelter Größe erstellt. Anschließend werden alle Elemente in das neu erstellte Array kopiert. Wir verwenden folgenden Ansatz:

Dynamisches Array in Java

Löschen Sie ein Element aus einem dynamischen Array

Wenn wir ein Element am angegebenen Index aus dem Array entfernen möchten, verwenden wir das removeAt(i) Methode. Die Methode analysiert die Indexnummer des Elements, das wir löschen möchten. Nach dem Löschen des Elements werden die verbleibenden Elemente (Elemente, die sich rechts vom gelöschten Element befinden) von der angegebenen Indexnummer nach links verschoben. Wir verwenden auch die Methode „remove()“, die ein Element vom Ende des Arrays löscht. Nach dem Verschieben der Elemente wird gespeichert 0 im Palast des letzten Elements. Lassen Sie es uns anhand eines Beispiels verstehen, wie wir in der folgenden Abbildung gezeigt haben.

Dynamisches Array in Java

Größenänderung eines dynamischen Arrays in Java

Wir müssen die Größe eines Arrays in zwei Szenarien ändern, wenn:

  • Das Array verwendet mehr Speicher als erforderlich.
  • Das Array belegt den gesamten Speicher und wir müssen Elemente hinzufügen.

Im ersten Fall verwenden wir die srinkSize() Methode zum Ändern der Größe Array . Es reduziert die Größe des Arrays. Dadurch wird zusätzlicher oder ungenutzter Speicher freigegeben. Im zweiten Fall verwenden wir die wachsenGröße() Methode zur Größenänderung des Arrays. Es erhöht die Größe des Arrays.

Dies ist ein teurer Vorgang, da er ein größeres Array erfordert und alle Elemente aus dem vorherigen Array kopiert und anschließend das neue Array zurückgibt.

Dynamisches Array in Java

Angenommen, im obigen Array müssen sechs weitere Elemente hinzugefügt werden und im Array ist kein Speicher mehr zum Speichern von Elementen übrig. In solchen Fällen vergrößern wir das Array mithilfe von wachsenGröße() Methode.

Suchmaschine und Beispiele
Dynamisches Array in Java

Initialisieren Sie ein dynamisches Array

Die Initialisierung des dynamischen Arrays ist dieselbe wie die des statischen Arrays. Betrachten Sie das folgende Java-Programm, das ein dynamisches Array initialisiert.

InitializeDynamicArray.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>

Lassen Sie uns die oben besprochenen Operationen in einem Java-Programm implementieren.

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