The ArrayList Class




An ArrayList is a collection class. It allows you to keep a list of objects (indexed at positions 0, 1, 2, etc.). You must add
import java.util.ArrayList;
to the top of your file.

Example:

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


Later, in some method:

   names.add("Jim");
   names.add("Jane");

   if (names.get(0).equals("Jim"))
     // do whatever



Some common methods:

add(some object) - adds the object (address of) to the end of the list
add(position, some object) - inserts the object (address of) at the given position (index)
get(position) - returns the address of the object at the given position (index)
remove(position) - removes the object (address of) at the given position (index)
clear() - removes all objects (address of each object) from the list



Example:


// this is a comment
// comments are ignored by the compiler (translater)


import java.util.ArrayList;

public class Sample10 {
        
    public Sample10() {
    }
    
    public static void main(String[] args) {
        
        
        // this is the title
        System.out.println("ArrayList");
        System.out.println();
        System.out.println();
        
        // we create our ArrayList which can hold String objects
        // list will refer to our ArrayList of String objects
        ArrayList  list = new ArrayList();
        
        // we will now add some String objects to our ArrayList
        list.add("Tom");
        list.add("Bill");
        list.add("Maria");
        list.add("Avi");
        list.add("Jill");
        
        
        // we will now print them out on the console
        // prints out Tom Bill Maria Avi Jill       
        for (int i=0; i<list.size(); i++)
        {
            System.out.print(list.get(i) + " ");
        }
        
        // we will remove the item in the 1 position (Bill)
        list.remove(1);


        // we will now print them out on the console
        // prints out Tom Maria Avi Jill        
        System.out.println();
        System.out.println();
        for (int i=0; i<list.size(); i++)
        {
            System.out.print(list.get(i) + " ");
        }
                
        // we will remove the item in the 2 position (Avi)
        list.remove("Avi");

        // we will now print them out on the console
        // prints out Tom Maria Jill        
        System.out.println();
        System.out.println();
        for (int i=0; i<list.size(); i++)
        {
            System.out.print(list.get(i) + " ");
        }


        System.out.println();
        System.out.println();
        
        
        
    }
}