logo

מערך דינמי ב-Java

מערך הוא גודל קבוע, הומוגני מבנה נתונים . המגבלה של מערכים היא שהם קבועים בגודלם. זה אומר שעלינו לציין את מספר האלמנטים בזמן הכרזה על המערך. כאן נשאלת השאלה, מה אם נרצה להכניס אלמנט ולא נשאר עוד מקום לאלמנט החדש? הנה, הרעיון של מערך דינמי בא לידי קיום. זה מוציא את גודל המערך באופן דינמי.

בחלק זה נבין מהו מערך דינמי, תכונות של המערך הדינמי, כיצד לשנות גודל של מערך דינמי, ו כיצד ליישם מערך דינמי ב-Java .

מה זה רמקול

מהו מערך דינמי?

המערך הדינמי הוא א גודל משתנה מבנה נתוני רשימה. זה גדל אוטומטית כשאנחנו מנסים להכניס אלמנט אם לא נשאר עוד מקום לאלמנט החדש. זה מאפשר לנו להוסיף ולהסיר אלמנטים. הוא מקצה זיכרון בזמן ריצה באמצעות הערימה. זה יכול לשנות את גודלו במהלך זמן הריצה.

ב Java , רשימת מערך הוא יישום שניתן לשינוי גודל. הוא מיישם את ממשק הרשימה ומספק את כל השיטות הקשורות לפעולות הרשימה. החוזק של המערך הדינמי הוא:

  • חיפוש מהיר
  • גודל משתנה
  • ידידותי למטמון

עבודה של מערך דינמי

במערך הדינמי, האלמנטים מאוחסנים ברציפות מתחילת המערך והשטח הנותר נותר ללא שימוש. אנו יכולים להוסיף את האלמנטים עד שהמרווח השמור יתכלה לחלוטין. כאשר השטח השמור נצרך ונדרש להוסיף כמה אלמנטים. במקרה כזה, יש להגדיל את המערך בגודל קבוע. שימו לב שלפני הוספת האלמנט, אנו מקצים מערך גדול יותר, מעתיקים את האלמנטים מהמערך ומחזירים את המערך החדש שנוצר.

מחרוזת מכילה java

דרך נוספת להוסיף אלמנט היא שתחילה, צור פונקציה שיוצרת מערך חדש בגודל כפול, מעתיקה את כל האלמנטים מהמערך הישן ומחזירה את המערך החדש. באופן דומה, אנו יכולים גם לכווץ את גודל המערך הדינמי.

גודל מול קיבולת

האתחול של מערך דינמי יוצר מערך בגודל קבוע. באיור הבא, למימוש המערך יש 10 מדדים. הוספנו חמישה אלמנטים למערך. כעת, למערך הבסיסי יש אורך של חמישה. לכן, אורך גודל המערך הדינמי הוא 5 והקיבולת שלו היא 10. המערך הדינמי עוקב אחר נקודת הקצה.

מערך דינמי ב-Java

תכונות של מערך דינמי

ב-Java, למערך הדינמי יש שלוש תכונות עיקריות: הוסף אלמנט, מחק אלמנט ושנה את גודלו של מערך.

הוסף אלמנט במערך דינמי

במערך הדינמי, נוכל ליצור מערך בגודל קבוע אם נצטרך להוסיף עוד כמה אלמנטים במערך. בדרך כלל, זה יוצר מערך חדש בגודל כפול. לאחר מכן, הוא מעתיק את כל האלמנטים למערך החדש שנוצר. אנו משתמשים בגישה הבאה:

הכנס למקלדת
מערך דינמי ב-Java

מחק אלמנט ממערך דינמי

אם אנחנו רוצים להסיר אלמנט מהמערך באינדקס שצוין, אנחנו משתמשים ב- removeAt(i) שיטה. השיטה מנתחת את מספר האינדקס של אותו אלמנט שאנו רוצים למחוק. לאחר מחיקת האלמנט, הוא מעביר את האלמנטים הנותרים (אלמנטים שהם ימינה לאלמנט שנמחק) שמאלה ממספר האינדקס שצוין. אנו משתמשים גם בשיטת remove() שמוחקת אלמנט מקצה המערך. לאחר העברת האלמנטים, הוא מאחסן 0 בארמון האלמנט האחרון. בואו נבין זאת באמצעות דוגמה, כפי שהראינו באיור הבא.

מערך דינמי ב-Java

שינוי גודל של מערך דינמי ב-Java

עלינו לשנות גודל של מערך בשני תרחישים אם:

  • המערך משתמש בזיכרון נוסף מהנדרש.
  • המערך תופס את כל הזיכרון ועלינו להוסיף אלמנטים.

במקרה הראשון, אנו משתמשים ב- srinkSize() שיטה לשנות את הגודל של מַעֲרָך . זה מקטין את גודל המערך. זה מפנה את הזיכרון הנוסף או שאינו בשימוש. במקרה השני, אנו משתמשים ב- growSize() שיטה לשנות את גודל המערך. זה מגדיל את גודל המערך.

זו פעולה יקרה כי היא דורשת מערך גדול יותר ומעתיקה את כל האלמנטים מהמערך הקודם לאחר מכן מחזירה את המערך החדש.

מערך דינמי ב-Java

נניח במערך הנ'ל, נדרש להוסיף שישה אלמנטים נוספים ובמערך, לא נשאר עוד זיכרון לאחסון אלמנטים. במקרים כאלה, אנו מגדלים את המערך באמצעות ה- growSize() שיטה.

מנהל Powershell
מערך דינמי ב-Java

אתחול מערך דינמי

האתחול של המערך הדינמי זהה למערך הסטטי. שקול את תוכנית Java הבאה המאתחלת מערך דינמי.

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>

בואו ליישם את הפעולות בתוכנית 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;>