Working with ArrayList
Create an ArrayList and use add, get, remove, size and clear to manage its items.
Apprentice · Java · Updated
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(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");

`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);

`remove(item)`
Removes an item from the list and shifts the remaining items to the left.
heroes.remove("Storm Hawk");

`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: anArrayList<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
nameout of its place in the lineup. - Put
nameat the front, index0. Everyone else keeps their order. - When
nameis 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.