null as an Element

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page        

Answer:

The equals(Object) method could be made more user friendly.

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.


import java.util.* ;

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 28:

If an array list is completely full, would adding a null force the list to grow?