Working with ArrayList

Create an ArrayList and use add, get, remove, size and clear to manage its items.

Apprentice · Java · Updated

By

Like arrays, when you create a new ArrayList, you must specify the data type that the ArrayList will store.

ArrayList lives in the java.util package, so import it at the top of the file.

import java.util.ArrayList;

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

`add(item)`

Add a new item to the end of the list. The ArrayList will automatically grow when it needs more space.

heroes.add("Storm Hawk");
heroes.add("Steel Comet");
heroes.add("Captain Lightning");
heroes.add("Shadow Fox");

add puts a new item after the last one in the list

`add(index, item)`

Add a new item at the specified position. The ArrayList will shift all items to the right and insert the new item.

heroes.add(2,"Jade Tiger");

Inserting Jade Tiger at index 2: Captain Lightning and Shadow Fox shift one place to the right

`get(index)`

Get the value at a specified index position. This works similarly to how you would get a value from an array: names[2].

String name = heroes.get(2);

get(2) returns the item at index 2, Jade Tiger

`remove(item)`

Removes an item from the list and shifts the remaining items to the left.

heroes.remove("Storm Hawk");

remove takes Storm Hawk out of the list and every item after it shifts one place to the left

`size()`

This returns the size of the list. It works like the array.length property.

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

`clear()`

This removes all elements in the list.

heroes.clear();

Do it: move a VIP to the front of the line

At the concert, people wait in a lineup. A person with a VIP pass skips ahead: they leave their place, everyone behind them moves up one, and they join the line at the very front.

The method gets two values:

  • lineup: an ArrayList<String> of the names in line, the front of the line first.
  • name: the person with the VIP pass. They are always somewhere in the lineup.

For example, Raj has the VIP pass:

ArrayList<String> lineup = new ArrayList<String>();
lineup.add("Ana");
lineup.add("Lee");
lineup.add("Raj");
lineup.add("Kim");
String name = "Raj";
Step The lineup
At the start Ana, Lee, Raj, Kim
Raj leaves his place, and Kim moves up Ana, Lee, Kim
Raj joins at the front, index 0 Raj, Ana, Lee, Kim

So moveToFront(lineup, "Raj") returns the list Raj, Ana, Lee, Kim.

Your job: write the method moveToFront(ArrayList<String> lineup, String name) so it returns the lineup, an ArrayList<String>, with the VIP at the front.

  • Take name out of its place in the lineup.
  • Put name at the front, index 0. Everyone else keeps their order.
  • When name is already first, the lineup ends up as it was.
  • Return the lineup.

Practiced live on the lesson page: write the Java right there and check it.

Cheat sheets