Add, insert, read, replace and remove items, and watch later items shift as the list changes.
Java · intermediate · 7 min · 11 steps · free
import java.util.ArrayList;
import java.util.List;
public class ArrayListDemo {
public static void main(String[] args) {
List<String> todo = new ArrayList<>();
todo.add("email");
todo.add("shop");
todo.add(1, "call"); // insert at index 1: later items shift right
String first = todo.get(0);
todo.set(2, "groceries"); // replace an item
todo.remove("email"); // later items shift left
boolean hasCall = todo.contains("call");
int size = todo.size();
System.out.println(todo + " " + first + " " + hasCall + " " + size);
}
}todo points to.todo points to.hasCall is created on the stack with the value true.size is created on the stack with the value 2.[call, groceries] email true 2.Answer: "a". Everything shifted right by one.
Answer: get(i). Reading by index is instant; inserting at the front shifts everything.
Stacks and Queues with ArrayDeque →