Dynamic Array

  1. Arrays in Java are dynamic in size (but not in type)

    Example: array size can change anytime during the program !
        int[] A;
    
        A = new int[10];  // Now A is an array of 10 elements   
        ....
        A = new int[50];  // Now A is an array of 50 elements   
    
    

  2. Example: a dynamically growing phone list...

       public class PhoneBook
       {
          private String name[];
          private String phone[];
          int nEntries;
    
          // Allocate space for n entries
          public PhoneBook(int n)
          {
             name  = new String[n];
             phone = new String[n];
    	 nEntries = 0;
          }
    
          // Insert name n & phone ph in this PhoneBook
          public void insertEntry(String n, String ph)
          {
             if (nEntries == this.name.length)
    	 {  // Filled up - expand
    	    expand(3);  // Add 3 more entries to phone book 
    	 }
    
    	 name[nEntries] = n;
    	 phone[nEntries] = ph;
    	 nEntries++;
          }
    
          // Expand phone book...
          private void expand(int n)
          {
    	 String[] helpName;
    	 String[] helpPhone;
    	 int i;
    
    	 // Make a longer array
    	 helpName = new String[name.length + n];
    	 helpPhone = new String[phone.length + n];
    
    	 // Copy old information over...
    	 for (i = 0; i < nEntries; i++)
    	 {
    	    helpName[i] = name[i];
    	    helpPhone[i] = phone[i];
    	 }
    
    	 // Set name & phone to the new array objects
    	 name = helpName;
    	 phone = helpPhone;
          }
    
          public void print()
          {
             int i;
    
    	 for (i = 0; i < nEntries; i++)
    	 {
    	    System.out.println(name[i] + "  " + phone[i]);
    	 }
       }
    
    

    DEMO Programs: