CS 1713: The ArrayList

The Java ArrayList class

The Java ArrayList class behaves like an array of objects that can grow automatically. Look at the documentation at http://java.sun.com/j2se/1.5/docs/api/java/util/ArrayList.html.

We will be using the newer syntax for the ArrayList that allows you to specify the type of object contained in the ArrayList. This is referred to as the generic ArrayList. It takes a little more work to set up this type of ArrayList, but it is safer and easier to use. It is slightly different from what is described in the textbook.

The ArrayList has methods to add objects at the end or at a specified position, remove a specific object or an object at a specified position, and return the index of a specified object.

Example 1: Create an ArrayList and add 100 randomly generated Integer objects to it.
   Random rand = new Random( );
   ArrayList<Integer> values = new ArrayList<Integer>( );
   for (int i = 0; i < 100; i++)
      values.add(rand.nextInt( ));

Notice the new syntax that uses angle brackets to specify the type of object that the ArrayList contains.

Example 2: Determine whether values of Example 1 has an object corresponding to the integer 500.

   boolean hasit = values.contains(new Integer(500));
   if (hasit)
       System.out.println("The values list contains 500");

Example 3: Declare an ArrayList that can contain Strings.
   ArrayList<String> myStrings;
An ArrayList must be initialized before it is used.

Example 4: Initialize the above ArrayList.

   myStrings = new ArrayList<String>();

Example 5: Declare and initialize an ArrayList of Strings in a single statement.

   ArrayList<String> myString = new ArrayList<String>();

Some important methods of ArrayList<E> are:

Example 6:Find the Rectangle of largest area and return it after removing it from the list.

   public Rectangle removeLargest(ArrayList<Rectangle> list) {
      if (list.size() == 0)
          return null;
      Rectangle largest = list.get(0);
      for (int i=1; i< list.size(); i++) {
          if (list.get(i).getArea() > largest.getArea())
              largest = list.get(i);
      list.remove(largest);
      return largest;
   }

ArrayLists differ from arrays in the following ways:


What do you do it you want an ArrayList of its?
You cannot do it directly since an ArrayList can only contain objects.
You can use a wrapper class.

The class Integer represents a single integer.

Java has ways to automatically convert between a primitive value such as an int and the corresponding wrapper class Integer, but you should not use these until you are more proficient.