Skip to content

Java ArrayList API

Java ArrayList — resizable-array implementation of the List interface.

1 class · 10 methods

ArrayList<E>

10 methods

Resizable-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

NameTypeDescription
eEElement to append.

Returns

boolean

Example

java
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

NameTypeDescription
indexint0-based index.

Returns

E

Example

java
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

NameTypeDescription
indexint0-based index.
elementENew element.

Returns

E

Example

java
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

NameTypeDescription
indexint0-based index.

Returns

E

Example

java
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

java
List<Integer> list = List.of(1, 2, 3);
list.size()  // 3
boolean isEmpty()

Return true if the list contains no elements.

Returns

boolean

Example

java
new ArrayList<>().isEmpty()  // true
List.of(1).isEmpty()         // false
boolean contains(Object o)

Return true if the list contains the specified element (uses equals).

Parameters

NameTypeDescription
oObjectElement to find.

Returns

boolean

Example

java
List<String> list = List.of("a", "b");
list.contains("a")  // true
list.contains("z")  // false
int indexOf(Object o)

Return the index of the first occurrence of o, or -1 if not found.

Parameters

NameTypeDescription
oObjectElement to find.

Returns

int

Example

java
List<String> list = List.of("a", "b", "a");
list.indexOf("a")  // 0
list.indexOf("z")  // -1
void clear()

Remove all elements from the list.

Returns

void

Example

java
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

java
List<String> list = List.of("a", "b");
Object[] arr = list.toArray();
// arr == ["a", "b"]
String[] sa = list.toArray(new String[0]);  // typed version