Incremental Java
ArrayList Test Class

Writing a Test Class

Let's try to get a better understanding of ArrayList by writing a simple test class. We'll call the test class, ArrayListTest.
public class ArrayListTest
{
   public static void main( String [] args )
   {
      ArrayList list = new ArrayList() ;

      // Prints "list has size 0"  
      System.out.println( "list has size: " + list.size() ) ;

      // Prints "list is empty? true"  
      System.out.println( "list is empty? " + list.isEmpty() ) ;
      
      list.add( "ape" ) ;
      list.add( "bat" ) ;
      list.add( "cat" ) ;
      list.add( "dog" ) ;
      list.add( "elk" ) ;

      // Prints "list has size 5"  
      System.out.println( "list has size: " + list.size() ) ;

      // Prints "list is empty? false"  
      System.out.println( "list is empty? " + list.isEmpty() ) ;
   }
}
Initially, list is a handle to an ArrayList that contains no objects. Then, we proceed to add 5 String objects to the ArrayList. We aren't required to put only String objects. Any object type could have been added.

When the objects are added, they are always added at the end. Thus, "ape" is added first, and is at index 0. "bat" is added second and is at index 1. "cat" is added third and is at index 2. "dog" is added fourth and is at index 3. "elk" is added fifth and is at index 4.

The order in which the strings are added matters. The ArrayList does not try to alphabetize them (we just added them in that order). If we had added "elk" first, it would have been at index 0.

Visualizing the ArrayList

This is how the ArrayList looks after inserting the 5 strings, from the previous section's main().

Index 0 1 2 3 4
Value "ape" "bat" "cat" "dog" "elk"

Suppose we had written the code as:

   public static void main( String [] args )
   {
      ArrayList list = new ArrayList() ;

      list.add( "dog" ) ;
      list.add( "bat" ) ;
      list.add( "elk" ) ;
      list.add( "cat" ) ;

   }
What would the list have looked like?

Here's the answer:

Index 0 1 2 3
Value "dog" "bat" "elk" "cat"

You see that the order the strings are entered in the list matters.