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

Don't Miss

  • Unity
    'Assassin's Creed Unity' preview: Ubisoft comes home to its urban origins
    Games Preview
  • Smart vending machine
    This smart vending machine will recommend drinks for you based on your gender and age
    Video
    Tech Buzz
  • Destiny
    The 'Destiny' beta: 7 things we absolutely love about Bungie's new franchise
    Games Feature
  • Wi-Fi
    Find out how to stretch your Wi-Fi signal where it has never gone before
    Tech Tips
  • Far Cry
    'Far Cry 4' exclusive: Animals, avalanches, oxygen, side content and much more
    Games Interview
  • Gamer ghost
    Gamer finds and plays with ghost of deceased father on a classic game
    Video
    Headlines