In Java, the List interface is a part of the java.util package and represents an ordered collection (also known as a sequence) of elements. Here’s the syntax and a list of commonly used methods in the List interface:
public interface List<E> extends Collection<E> {
// Methods
}
Code language: PHP (php)
Methods:
- Adding Elements:
- boolean add(E e): Appends the specified element to the end of this list (optional operation).
- void add(int index, E element): Inserts the specified element at the specified position in this list (optional operation).
- Removing Elements:
- boolean remove(Object o): Removes the first occurrence of the specified element from this list, if it is present (optional operation).
- E remove(int index): Removes the element at the specified position in this list (optional operation).
- Accessing Elements:
- E get(int index): Returns the element at the specified position in this list.
- E set(int index, E element): Replaces the element at the specified position in this list with the specified element (optional operation).
- Querying List Information:
- int size(): Returns the number of elements in this list.
- boolean isEmpty(): Returns true if this list contains no elements.
- Searching and Checking:
- boolean contains(Object o): Returns true if this list contains the specified element.
- int indexOf(Object o): Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.
- Sublists:
- List<E> subList(int fromIndex, int toIndex): Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive.
- Bulk Operations:
- boolean containsAll(Collection<?> c): Returns true if this list contains all of the elements of the specified collection.
- boolean addAll(Collection<? extends E> c): Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection’s iterator (optional operation).
- Conversion to Array:
- Object[] toArray(): Returns an array containing all of the elements in this list in proper sequence.
- Clearing the List:
- void clear(): Removes all of the elements from this list (optional operation).
import java.util.*; public class ListExample { public static void main(String[] args) { List<String> list = new ArrayList<>(); // Adding elements list.add("Java"); list.add("Python"); list.add("C++"); // Accessing elements System.out.println("Element at index 1: " + list.get(1)); // Removing elements list.remove("Python"); // Iterating over elements for (String language : list) { System.out.println(language); } // Checking if list contains an element System.out.println("List contains Java: " + list.contains("Java")); } }