logo

Array dinamico in Java

Un array è di dimensione fissa, omogeneo struttura dati . La limitazione degli array è che hanno dimensioni fisse. Significa che dobbiamo specificare il numero di elementi durante la dichiarazione dell'array. Qui sorge la domanda: cosa succede se vogliamo inserire un elemento e non c'è più spazio per il nuovo elemento? Qui, il concetto di matrice dinamica viene all'esistenza. Spende la dimensione dell'array in modo dinamico.

In questa sezione capiremo cos'è un array dinamico, caratteristiche dell'array dinamico, come ridimensionare un array dinamico, E come implementare l'array dinamico in Java .

Cos'è un array dinamico?

L'array dinamico è a dimensione variabile elencare la struttura dei dati. Cresce automaticamente quando proviamo a inserire un elemento se non c'è più spazio per il nuovo elemento. Ci permette di aggiungere e rimuovere elementi. Alloca memoria in fase di esecuzione utilizzando l'heap. Può cambiare dimensione durante l'esecuzione.

In Giava , Lista di array è un'implementazione ridimensionabile. Implementa l'interfaccia List e fornisce tutti i metodi relativi alle operazioni sugli elenchi. La forza dell'array dinamico è:

  • Ricerca rapida
  • Dimensione variabile
  • Adatto alla cache

Funzionamento dell'array dinamico

Nell'array dinamico gli elementi vengono memorizzati in modo contiguo dall'inizio dell'array e lo spazio rimanente rimane inutilizzato. Possiamo aggiungere gli elementi fino a consumare completamente lo spazio riservato. Quando lo spazio riservato viene consumato ed è necessario aggiungere alcuni elementi. In tal caso, è necessario aumentare le dimensioni dell'array di dimensione fissa. Tieni presente che prima di aggiungere l'elemento, allochiamo un array più grande, copiamo gli elementi dall'array e restituiamo l'array appena creato.

stringa comparabile

Un altro modo per aggiungere un elemento è innanzitutto creare una funzione che crei un nuovo array di dimensione doppia, copi tutti gli elementi dal vecchio array e restituisca il nuovo array. Allo stesso modo, possiamo anche ridurre la dimensione dell'array dinamico.

Dimensioni e capacità

L'inizializzazione di un array dinamico crea un array a dimensione fissa. Nella figura seguente, l'implementazione dell'array ha 10 indici. Abbiamo aggiunto cinque elementi all'array. Ora, l'array sottostante ha una lunghezza di cinque. Pertanto, la lunghezza della dimensione dell'array dinamico è 5 e la sua capacità è 10. L'array dinamico tiene traccia dell'endpoint.

Array dinamico in Java

Caratteristiche dell'array dinamico

In Java, l'array dinamico ha tre caratteristiche chiave: Aggiungi elemento, elimina un elemento e ridimensiona un array.

Aggiungi elemento in una matrice dinamica

Nell'array dinamico, possiamo creare un array di dimensioni fisse se volessimo aggiungere altri elementi nell'array. Di solito crea un nuovo array di doppia dimensione. Successivamente, copia tutti gli elementi nell'array appena creato. Utilizziamo il seguente approccio:

Array dinamico in Java

Elimina un elemento da una matrice dinamica

Se vogliamo rimuovere un elemento dall'array in corrispondenza dell'indice specificato, utilizziamo il metodo rimuoviAt(i) metodo. Il metodo analizza il numero di indice dell'elemento che vogliamo eliminare. Dopo aver eliminato l'elemento, sposta gli elementi rimanenti (elementi che si trovano a destra dell'elemento eliminato) a sinistra dal numero di indice specificato. Usiamo anche il metodo Remove() che cancella un elemento dalla fine dell'array. Dopo aver spostato gli elementi, immagazzina 0 al palazzo dell'ultimo elemento. Capiamolo attraverso un esempio, come abbiamo mostrato nella figura seguente.

numero casuale in Java
Array dinamico in Java

Ridimensionamento di un array dinamico in Java

Dobbiamo ridimensionare un array in due scenari se:

  • L'array utilizza memoria aggiuntiva rispetto a quella richiesta.
  • L'array occupa tutta la memoria e dobbiamo aggiungere elementi.

Nel primo caso utilizziamo il file SrinkSize() metodo per ridimensionare il file vettore . Riduce la dimensione dell'array. Libera la memoria extra o inutilizzata. Nel secondo caso utilizziamo il file cresceredimensione() metodo per ridimensionare l'array. Aumenta la dimensione dell'array.

È un'operazione costosa perché richiede un array più grande e copia tutti gli elementi dall'array precedente, dopodiché restituisce il nuovo array.

Array dinamico in Java

Supponiamo che nell'array precedente sia necessario aggiungere altri sei elementi e che nell'array non sia rimasta più memoria per memorizzare gli elementi. In questi casi, ingrandiamo l'array utilizzando il file cresceredimensione() metodo.

Array dinamico in Java

Inizializza un array dinamico

L'inizializzazione dell'array dinamico è la stessa dell'array statico. Considera il seguente programma Java che inizializza un array dinamico.

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

Implementiamo le operazioni in un programma Java di cui abbiamo discusso sopra.

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