go to previous page   go to home page   go to next page highlighting

Answer:

headPtr = null;

The garbage collector will recycle all the orphan nodes.


get()

The get(int index) method returns the value of a node at a particular index. Indexes start at zero and go up to the length of the list minus one. This is just like arrays and ArrayList.

What happens if the index is out of bounds? The methods throws an IndexOutOfBoundsException. This effectively stops the program.

Here is the method:


  // get the value at indexof the list
  //
  int get( int index ) throws IndexOutOfBoundsException
  {
    if ( isEmpty() )
      throw new IndexOutOfBoundsException();   
      
    Node p = headPtr;
    int counter = 0;
    while ( counter<index && p != null )
    {      
      p = p.getNext();
      counter++ ;
    }
    if ( index==counter )
      return p.getValue();
    else
      throw new IndexOutOfBoundsException();   
  }                

If the list is empty, an IndexOutOfBoundsException is thrown no matter what the index. Otherwise, a counter starts out at zero (for the first node of the list) and is incremented node by node as the list is traversed. When the counter is equal to the index, the value in that node is returned. Or, if the list is too short, an IndexOutOfBoundsException is thrown.


QUESTION 14:

Would a set( int index, int value ) method be useful?


go to previous page   go to home page   go to next page