🚀 TechFlow Now

← Back to Resources

Java List Methods

add(E e)

Adds an element to the list.

List list = new ArrayList<>();
list.add("Java");
list.add("Python");

add(int index, E element)

Inserts the element at the specified position.

list.add(1, "C++");

get(int index)

Returns the element at the specified index.

System.out.println(list.get(0)); // Java

remove(int index)

Removes the element at the specified index.

list.remove(1); // Removes C++

remove(Object o)

Removes the first occurrence of the specified element.

list.remove("Python");

size()

Returns the number of elements in the list.

System.out.println(list.size()); // 1

contains(Object o)

Returns true if the list contains the specified element.

System.out.println(list.contains("Java")); // true

isEmpty()

Returns true if the list has no elements.

System.out.println(list.isEmpty()); // false

clear()

Removes all elements from the list.

list.clear();

indexOf(Object o)

Returns the index of the first occurrence of the element.

list.add("Python");
list.add("Java");
System.out.println(list.indexOf("Java")); // 1

lastIndexOf(Object o)

Returns the index of the last occurrence of the element.

System.out.println(list.lastIndexOf("Java")); // 1

set(int index, E element)

Replaces the element at the specified position.

list.set(0, "C#");