A lot of people ask me how to use an ArrayList and also ask what is the advantage of an ArrayList over a standard Array.
If the data has a known number of elements or small fixed size upper bound, arrays are often the best choice. However, many data storage problems are not that simple. The main advantage to an ArrayList is that it automatically expands as data is added. A disadvantage is that an ArrayList cannot work with primitive types.
Here is a quick example to show you how to add, print, and remove data from an ArrayList:
// Import ArrayList import java.util.ArrayList; public class ArrayListExample { /** * JavaProgrammingForums.com */ public static void main(String[] args) { // Construct a new empty ArrayList for type String ArrayList<String> al = new ArrayList<String>(); // Fill ArrayList (index, String) al.add(0, "Java"); al.add(1, "Programming"); al.add(2, "Forums"); al.add(3, ".com"); // Convert ArrayList to Object array Object[] elements = al.toArray(); // Print Object content for (int a = 0; a < elements.length; a++) { System.out.println(elements[a]); } // Remove item from ArrayList al.remove(3); // Clear entire ArrayList al.clear(); } }