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

Answer:

The equals(Object) method could be made case insensitive.

Another good modification of the program would be to allow the user to put new entries into the list.


null as an Element

An ArrayList element can be an object reference or the value null. When a cell contains null, the cell is not considered to be empty. The picture shows empty cells with an "X" and cells that contain a null with null.

ArrayList with nulls
import java.util.* ;

public class ArrayListEgFive
{

  public static void main ( String[] args)
  {
    // Create an ArrayList that holds references to String
    ArrayList<String> names = new ArrayList<String>();

    // Add three Object references and two nulls
    names.add("Amy");
    names.add(null);
    names.add("Bob");
    names.add(null);
    names.add("Cindy");
    System.out.println("size: " + names.size() );
       
    // Access and print out the Objects
    for ( int j=0; j<names.size(); j++ )
      System.out.println("element " + j + ": " + names.get(j) );
  }
}

The program prints out:

size: 5
element 0: Amy
element 1: null
element 2: Bob
element 3: null
element 4: Cindy

The cells that contain null are not empty, and contribute to the size of the list. It is confusing when nulls are elements of some cells. Don't write your programs to do this unless there is a good reason.


QUESTION 30:

If you wish to remove Cindy from the ArrayList, should you set that cell to null?

names.set( 4, null )