logo

Динамички низ у Јави

Низ је фиксне величине, хомоген структура података . Ограничење низова је да су фиксне величине. То значи да морамо навести број елемената док декларишемо низ. Овде се поставља питање шта ако желимо да убацимо елемент и нема више простора за нови елемент? Овде је концепт динамички низ долази у постојање. Динамички проширује величину низа.

У овом одељку ћемо разумети шта је динамички низ, карактеристике динамичког низа, како променити величину динамичког низа, и како имплементирати динамички низ у Јави .

Шта је динамички низ?

Динамички низ је а променљива величина структура података листе. Аутоматски расте када покушамо да убацимо елемент ако нема више простора за нови елемент. Омогућава нам да додајемо и уклањамо елементе. Он додељује меморију у време извршавања помоћу гомиле. Може да промени своју величину током времена рада.

Ин Јава , Низ листа је имплементација која може да се промени. Он имплементира интерфејс листе и обезбеђује све методе везане за операције листе. Снага динамичког низа је:

  • Брзо тражење
  • Променљива величина
  • Цацхе-фриендли

Рад динамичког низа

У динамичком низу, елементи се чувају непрекидно од почетка низа, а преостали простор остаје неискоришћен. Можемо додавати елементе док се резервисани размак у потпуности не потроши. Када се резервисани простор потроши и потребно је додати неке елементе. У том случају, потребно је повећати величину низа фиксне величине. Имајте на уму да пре додавања елемента додељујемо већи низ, копирамо елементе из низа и враћамо новокреирани низ.

Други начин да додате елемент је да прво направите функцију која креира нови низ двоструке величине, копира све елементе из старог низа и враћа нови низ. Слично томе, такође можемо смањити величину динамичког низа.

Величина у односу на капацитет

Иницијализација динамичког низа ствара низ фиксне величине. На следећој слици, имплементација низа има 10 индекса. Додали смо пет елемената у низ. Сада, основни низ има дужину од пет. Дакле, дужина величине динамичког низа је 5, а његов капацитет је 10. Динамички низ прати крајњу тачку.

Динамички низ у Јави

Карактеристике динамичког низа

У Јави, динамички низ има три кључне карактеристике: Додајте елемент, избришите елемент и промените величину низа.

Додајте елемент у динамички низ

У динамичком низу, можемо креирати низ фиксне величине ако морамо да додамо још неке елементе у низ. Обично креира нови низ двоструке величине. Након тога копира све елементе у новостворени низ. Користимо следећи приступ:

Динамички низ у Јави

Избришите елемент из динамичког низа

Ако желимо да уклонимо елемент из низа на наведеном индексу, користимо уклонити Ат(и) методом. Метода анализира број индекса тог елемента који желимо да избришемо. Након брисања елемента, помера преостале елементе (елементе који су десно од обрисаног елемента) улево од наведеног индексног броја. Такође користимо методу ремове() која брише елемент са краја низа. Након померања елемената, он се складишти 0 у палати последњег елемента. Хајде да то разумемо кроз пример, као што смо показали на следећој слици.

Динамички низ у Јави

Промена величине динамичког низа у Јави

Морамо да променимо величину низа у два сценарија ако:

  • Низ користи додатну меморију него што је потребно.
  • Низ заузима сву меморију и морамо да додамо елементе.

У првом случају користимо сринкСизе() метод за промену величине низ . Смањује величину низа. То ослобађа додатну или неискоришћену меморију. У другом случају користимо гровСизе() метод за промену величине низа. Повећава величину низа.

То је скупа операција јер захтева већи низ и копира све елементе из претходног низа након чега враћа нови низ.

Динамички низ у Јави

Претпоставимо да је у горњем низу потребно додати још шест елемената и да у низу више нема меморије за складиштење елемената. У таквим случајевима, ми повећавамо низ користећи гровСизе() методом.

Динамички низ у Јави

Иницијализујте динамички низ

Иницијализација динамичког низа је иста као и статичког низа. Размотрите следећи Јава програм који иницијализује динамички низ.

ИнитиализеДинамицАрраи.јава

 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>

Хајде да имплементирамо операције у Јава програму о којима смо горе говорили.

ДинамицАрраиЕкампле1.јава

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