ArrayList<E>
10 methodsResizable-array implementation of the List interface. Permits null and all elements.
boolean add(E e)Append the specified element to the end of the list.
Parameters
| Name | Type | Description |
|---|---|---|
| e | E | Element to append. |
Returns
boolean
Example
List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
// list == ["a", "b"]E get(int index)Return the element at the specified position. Throws IndexOutOfBoundsException.
Parameters
| Name | Type | Description |
|---|---|---|
| index | int | 0-based index. |
Returns
E
Example
List<String> list = List.of("a", "b", "c");
list.get(0) // "a"
list.get(2) // "c"E set(int index, E element)Replace the element at the specified position. Returns the previous element.
Parameters
| Name | Type | Description |
|---|---|---|
| index | int | 0-based index. |
| element | E | New element. |
Returns
E
Example
List<String> list = new ArrayList<>(List.of("a", "b"));
String old = list.set(0, "x");
// old == "a", list == ["x", "b"]E remove(int index)Remove the element at the specified position. Returns the removed element.
Parameters
| Name | Type | Description |
|---|---|---|
| index | int | 0-based index. |
Returns
E
Example
List<String> list = new ArrayList<>(List.of("a", "b", "c"));
String r = list.remove(1);
// r == "b", list == ["a", "c"]int size()Return the number of elements in the list.
Returns
int
Example
List<Integer> list = List.of(1, 2, 3);
list.size() // 3boolean isEmpty()Return true if the list contains no elements.
Returns
boolean
Example
new ArrayList<>().isEmpty() // true
List.of(1).isEmpty() // falseboolean contains(Object o)Return true if the list contains the specified element (uses equals).
Parameters
| Name | Type | Description |
|---|---|---|
| o | Object | Element to find. |
Returns
boolean
Example
List<String> list = List.of("a", "b");
list.contains("a") // true
list.contains("z") // falseint indexOf(Object o)Return the index of the first occurrence of o, or -1 if not found.
Parameters
| Name | Type | Description |
|---|---|---|
| o | Object | Element to find. |
Returns
int
Example
List<String> list = List.of("a", "b", "a");
list.indexOf("a") // 0
list.indexOf("z") // -1void clear()Remove all elements from the list.
Returns
void
Example
List<String> list = new ArrayList<>(List.of("a", "b"));
list.clear();
// list == []Object[] toArray()Return an array containing all elements in the list in proper sequence.
Returns
Object[]
Example
List<String> list = List.of("a", "b");
Object[] arr = list.toArray();
// arr == ["a", "b"]
String[] sa = list.toArray(new String[0]); // typed version