Skip to main content
  1. Tech
  2. Gadgets & Tech
  3. Internet

A simple Java ArrayList example

See also

The ArrayList is one of the most useful Java data structures. It is also very easy to use. Here is a simple example of the Java ArrayList.

1. Import the package. To use the Java ArrayList, include this import statement at the top of your class file: import java.util.ArrayList;

2. Instantiate the ArrayList. When you instantiate a Java ArrayList, you must specify the type of objects that the ArrayList will hold. Here is how you create an ArrayList of String objects: ArrayList<String> alFruits = new ArrayList<String>();

3. Add items to the ArrayList. To add items to an ArrayList, use the add() method: alFruits.add("apple");

4. Remove items from the ArrayList. To remove items from an ArrayList, use the remove() method: alFruits.remove("apple");

5. Retrieve items from the ArrayList. To retrieve an item from an ArrayList, use the get() method. This method requires they array index as a parameter: String sFruit = alFruits.get(0);

6. Iterate through the ArrayList. Looping through the objects in an ArrayList is easy. The size() method gives you the upper bound of the list.

Here is a complete program that uses a Java ArrayList:

import java.util.ArrayList;

public class Test {

public static void main(String[] args) {

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

alFruits.add("apple");
alFruits.remove("apple");
alFruits.add("orange");
alFruits.add("pear");

for (int i=0; i < alFruits.size(); i++) {
String sFruit = alFruits.get(i);
System.out.println(sFruit);
}
}

}

Here is the output:
orange
pear

This simple example shows how to use a Java ArrayList. The ArrayList is fairly simple to use, but it is one of the most powerful data structures in the Java programming language.

For more articles, please subscribe, add or follow me here.

Comments

Advertisement