Java Collections – ArrayList Example

Arraylist class is a resizable array implementation of the List interface. It is probably the most widely used class of the Collections because of the flexibility it provides. Developers choose Arraylist over Array because it offers the flexibility of growing the collection as needed with little in terms of penalty. Arrays suffer because of their fixed length so if they get full we cannot add any more elements to them. Also, they do not automatically shrink if elements are removed from them. ArrayList can dynamically grow and shrink as needed.

Big-O Notation

The ArrayList implementation provides O(n) for add() operations and O(1) for get() and remove() operations.

Creating a ArrayList

This was the old-way prior to Generics.

ArrayList  HallOfFameMembers = new ArrayList();

or

Collection HallOfFameMembers = new ArrayList();

Generics

If you look closely, you will notice that I am using Generics to limit the type to String. Generics add stability to your code, by having the computer detect type incompatibilities during compile-time. These runtime bugs would be more difficult to debug if left unchecked.

Collection<Player> HallOfFameMembers = new ArrayList<Player>();

Adding elements

Adding elements to the ArrayList is done by using the add(Object obj) method.

// Add elements to our ArrayList
HallOfFameMembers.add(babe);
HallOfFameMembers.add(ty);
HallOfFameMembers.add(lou);
HallOfFameMembers.add(ted);
HallOfFameMembers.add(hank);
HallOfFameMembers.add(yogi);
HallOfFameMembers.add(willie);

Removing elements

Removing elements is just a matter of calling the remove(Object obj) method.

HallOfFameMembers.remove(yogi);
HallOfFameMembers.remove(ted);

Size of Collection

Returning the number of elements in a ArrayList is as easy as calling the size() method.

HallOfFameMembers.size();

Iterating through the Collection (Using foreach)

Java 1.5 and above provides a foreach loop, which makes it much easier to iterate over the entire collection. This is my preferred way of doing it.

// Loop through the collection of ArrayList
for (Player player : HallOfFameMembers) {
  count++;
  System.out.format("[%d]: %s, played for %s, started career in %d", 
     count, player.getPlayerName(), player.getTeam(), 
     player.getStartYear());
}

Iterating through the Collection (Using for Loop)

for (int i = 0; i < HallOfFameMembers.size(); i++) {
  Player player = HallOfFameMembers.get(i);
  System.out.format("[%d]: %s, played for %s, started career in %d", 
     i, player.getPlayerName(), 
     player.getTeam(), player.getStartYear());
}

Iterating through the Collection (Using iterator)

// Loop through the collection of HallOfFameMembers
int count = 0;
Iterator<Player> iter=(Iterator<Player>) HallOfFameMembers.iterator();
while (iter.hasNext()) {
  count++;
  Player player = iter.next();
  System.out.format("[%d]: %s, played for %s, started career in %d", 
      count, player.getPlayerName(), 
      player.getTeam(), player.getStartYear());
}

Full Program Listing (ArrayListExample.java)

package com.avaldes.tutorials;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

public class ArrayListExample {
    
  public static void main(String[] args) {
    ArrayList<Player> HallOfFameMembers = new ArrayList<Player>();

    // Check to see if the ArrayList is empty
    System.out.println("Is ArrayList Empty: " + HallOfFameMembers.isEmpty());
    
    //Create all the players
    Player babe = new Player("Babe Ruth", 1914, "New York Yankees");
    Player ty = new Player("Ty Cobb", 1905, "Detroit Tigers");
    Player lou = new Player("Lou Gehrig", 1923, "New York Yankees");
    Player ted = new Player("Ted Williams", 1939, "Boston Redsox");
    Player hank = new Player("Hank Aaron", 1954, "Atlanta Braves");
    Player yogi = new Player("Yogi Berra", 1946, "New York Yankees");
    Player willie = new Player("Willie Mays", 1951, "San Francisco Giants");
    Player roberto=new Player("Roberto Clemente",1955,"Pittsburgh Pirates");
    Player mickey= new Player("Mickey Mantle", 1951, "New York Yankees");
    Player tom = new Player("Tom Seaver", 1967, "New York Mets");
    Player nolan = new Player("Nolan Ryan", 1966, "Texas Rangers");
    Player amaury = new Player("Amaury Valdes", 1975, "Newark Bears");

    System.out.println("Adding 10 elements...");
    // Add elements to our ArrayList
    HallOfFameMembers.add(babe);
    HallOfFameMembers.add(ty);
    HallOfFameMembers.add(lou);
    HallOfFameMembers.add(ted);
    HallOfFameMembers.add(hank);
    HallOfFameMembers.add(yogi);
    HallOfFameMembers.add(willie);
    HallOfFameMembers.add(roberto);
    HallOfFameMembers.add(mickey);
    HallOfFameMembers.add(tom);
    HallOfFameMembers.add(nolan);
    
    // Add null values -- Allowed
    System.out.println("Adding null element...");
    HallOfFameMembers.add(null);
    
    // Check if Willie Mays is in my List
    System.out.println("Checking if Willie Mays is in HallOfFameMembers" 
                                     + HallOfFameMembers.contains(willie));
    System.out.println("Checking if Amaury Valdes is in HallOfFameMembers" 
                                     + HallOfFameMembers.contains(amaury));
    
    // Adding duplicate records
    HallOfFameMembers.add(lou);
    HallOfFameMembers.add(babe);
    HallOfFameMembers.add(yogi);
    
    // Display the number of elements in ArrayList
    System.out.println("nSize of ArrayList: " + HallOfFameMembers.size());

    // Check to see if the ArrayList is empty
    System.out.println("Is ArrayList Empty: " 
                                          + HallOfFameMembers.isEmpty());

    // Display the ArrayList object
    System.out.println(HallOfFameMembers);

    // Remove the null entry in HallOfFameMembers
    HallOfFameMembers.remove(null);
    
    // Display the ArrayList object
    System.out.println(HallOfFameMembers);
    
    // Display the ArrayList using foreach loop
    System.out.println("Displaying the full List of Baseball 
                                              HallOfFameMembers");
    count = 0;
    for (Player player : HallOfFameMembers) {
      count++;
      System.out.format("[%d]: %s, played for %s, 
         started career in %d", count, player.getPlayerName(), 
         player.getTeam(), player.getStartYear());
    }
  } 
}

Full Program Listing (Player.java)

package com.avaldes.tutorials;

public class Player {
  private String playerName;
  private int startYear;
  private String  team;
  
  public Player(String name, int year, String team) {
    setPlayerName(name);
    setStartYear(year);
    setTeam(team);
  }
  
  public String getPlayerName() {
    return playerName;
  }
  public void setPlayerName(String playerName) {
    this.playerName = playerName;
  }
  public int getStartYear() {
    return startYear;
  }
  public void setStartYear(int startYear) {
    this.startYear = startYear;
  }
  public String getTeam() {
    return team;
  }
  public void setTeam(String team) {
    this.team = team;
  } 

  @Override
  public String toString() {
     return playerName;
  }
}

Output

Is ArrayList Empty: true
Adding 10 elements...
Adding null element...

Checking if Willie Mays is in HallOfFameMembers... true
Checking if Amaury Valdes is in HallOfFameMembers... false

Size of ArrayList: 15
Is ArrayList Empty: false

[Babe Ruth, Ty Cobb, Lou Gehrig, Ted Williams, Hank Aaron, Yogi Berra, 
Willie Mays, Roberto Clemente, Mickey Mantle, Tom Seaver, Nolan Ryan, 
null, Lou Gehrig, Babe Ruth, Yogi Berra]
[Babe Ruth, Ty Cobb, Lou Gehrig, Ted Williams, Hank Aaron, Yogi Berra, 
Willie Mays, Roberto Clemente, Mickey Mantle, Tom Seaver, Nolan Ryan, 
Lou Gehrig, Babe Ruth, Yogi Berra]

Displaying the full List of Baseball HallOfFameMembers...
[1]: Babe Ruth, played for New York Yankees, started career in 1914
[2]: Ty Cobb, played for Detroit Tigers, started career in 1905
[3]: Lou Gehrig, played for New York Yankees, started career in 1923
[4]: Ted Williams, played for Boston Redsox, started career in 1939
[5]: Hank Aaron, played for Atlanta Braves, started career in 1954
[6]: Yogi Berra, played for New York Yankees, started career in 1946
[7]: Willie Mays, played for San Francisco Giants, started career in 1951
[8]: Roberto Clemente, played for Pittsburgh Pirates, started career in 1955
[9]: Mickey Mantle, played for New York Yankees, started career in 1951
[10]: Tom Seaver, played for New York Mets, started career in 1967
[11]: Nolan Ryan, played for Texas Rangers, started career in 1966
[12]: Lou Gehrig, played for New York Yankees, started career in 1923
[13]: Babe Ruth, played for New York Yankees, started career in 1914
[14]: Yogi Berra, played for New York Yankees, started career in 1946

Other Related Posts

Map Examples

List Examples

Set Examples

Please Share Us on Social Media

Facebooktwittergoogle_plusredditpinterestlinkedinmail

Leave a Reply

Your email address will not be published. Required fields are marked *