A better way to add and delete elements in arrays

  • Dynamic arrays (a.k.a. ArrayList in Java) consists of:

    1. A (fixed size) array

    2. A count of the actual number of elements stored in the array:

      Schematically:

      Currently, there are 2 values stored in the array

A better way to add and delete elements in arrays

  • Dynamic arrays (a.k.a. ArrayList in Java) consists of:

    1. Inserting a new value will increase the count

    2. If the array is not full, we do not need to increase its size

      Schematically: add(8) will result in:

      Now there are 3 values stored in the array

  • The array is increased only when the add( ) operation encounters a full array

  • The array is reduced when the occupancy drops below a certain threshold

A better way to add and delete elements in arrays

  • When the array is full:

    The add( ) method will increase the array size by approximately twice the original size:

    This will avoid frequent copy operations !

The array doubling algorithm

  • A commonly used algorithm to implement a dynamic array is array doubling:

    The array doubling algorithm:

       temp = new int[ 2*x.length ];
    
       for ( int i = 0; i < x.length; i++ )
           temp[i] = x[i];
    
       x = temp;
    

The array doubling algorithm

  • We create a new array that is twice the size of the original array:

    The array doubling algorithm:

       temp = new int[ 2*x.length ];
    
       for ( int i = 0; i < x.length; i++ )
           temp[i] = x[i];
    
       x = temp;
    

The array doubling algorithm

  • Copy the elements over to the new array:

    The array doubling algorithm:

       temp = new int[ 2*x.length ];
    
       for ( int i = 0; i < x.length; i++ )
           temp[i] = x[i];
    
       x = temp;
    

The array doubling algorithm

  • Make x reference to the new array:

    The array doubling algorithm:

       temp = new int[ 2*x.length ];
    
       for ( int i = 0; i < x.length; i++ )
           temp[i] = x[i];
    
       x = temp;
    

The array reduction algorithm is similar -- we will discuss more about array reduction later (Stack)

The ArrayList class in Java's library   animation:

  • The ArrayList class in Java implements a dynamic (resizable) array

  • The ArrayList class is in the package java.util

  • To use the ArrayList class, you must specify the following import statement:

       import java.util.ArrayList; 

  • Syntax to define an ArrayList (reference) variable:

       ArrayList<ObjectType> varName;  // Generic class !

  • Syntax to create an ArrayList object:

       new ArrayList<ObjectType>(); 

    The ArrayList object will start with a array of limited size (about 10)

Example creating an ArrayList object

  • Example instantiating an ArrayList object to store int values:

       ArrayList<Integer> numbers = new ArrayList<Integer>();
    
    or:
    
       ArrayList<Integer> numbers = new ArrayList<>();
    

    Note: we must use an object type to instantiate an ArrayList

  • Example instantiating an ArrayList object to store String objects:

       ArrayList<String> a = new ArrayList<String>();
    
    or:
    
       ArrayList<String> a = new ArrayList<>();
    

Some commonly used methods in the ArrayList class

  • size():

    • returns the actualy number of elements in the ArrayList

      E.g.:   int n = numbers.size()

  • toString( ):

    • returns a String representation of all elements stored in the ArrayList

      E.g.:   System.out.println( numbers );

    Note/Recall: println( ) invokes toString( ) in order to print an object !

Inserting and removing elements in an ArrayList

  • add(E e):

    • appends the element e to end of the ArrayList
      [E is the declared data type of the ArrayList elements]

      E.g.:   numbers.add(99);

  • add(int index, E elem):

    • inserts the element e at index index and shifts any subsequent items to the right

      E.g.:   numbers.add(0, 99); // Add 99 as the first element

  • remove(int index):

    • removes the element e at index index and shifts all remaining items to the left

      E.g.:   numbers.add(0); // Removes the first element

Retrieving and updating elements in an ArrayList

  • get(int index):

    • returns the element stored at the index index

      E.g.:   int n = numbers.get(1); // Retrieve the 2nd element

  • set(int index, E elem):

    • Replaces the element at index index with the element elem.

      E.g.:   numbers.set(0, 99); // Update first element to 99


  • Note:

    • If the element at the index does not exist, get( ) and set( ) will throw IndexOutOfBoundsException.

DEMO: 08-arraylist/01-arraylist/Demo.java

Iterating through an ArrayList

  • Using a regular for-loop and get(index):

        for (int i = 0; i < numbers.size(); i++ )
            System.out.println( numbers.get(i) );

  • Using a foreach loop:

        for ( int item: numbers )
            System.out.println( item )

    Note: a foreach loop can not be used to update array elements

  • Using a iterator object:

        Iterator<Integer> numItr = numbers.iterator();
    
        while ( numItr.hasNext() )
            System.out.println( numItr.next() )

DEMO: demo/08-arraylist/01-arraylist/Demo2.java

Java's Iterator interface and Iterable interface

  • Iterator is an interface (class containing all virtual methods) in java.util.Iterator

  • An object that implements the Iterator interface must provide at least the following methods:

      hasNext():  returns true if the iteration has more elements
    
      next():     return the next element in the iteratinr
    

  • An Iterator allows the user to iterate over the elements stored in a Iterable interface


  • An object is Iterable if implements the java.util.Iterable interface

    • It must implement the iterator() method that returns an Iterator object

You will see an example of iterator implementation when we discuss linked lists

Arrays vs ArrayList

  • Arrays:

    • Pros:

      • Uses less memory
      • Can store primitive types
      • Can be multi-dimensional

    • Cons:

      • Size cannot change
      • Hard to add/remove elements

Arrays vs ArrayList

  • ArrayLists:

    • Cons:

      • Uses more memory
      • Can not store primitive types
      • Can only be one-dimensional

    • Pros:

      • Size is dynamic
      • Easy to add/remove elements