In this tutorial, we will learn about the List interface and its methods in Java.
The List interface extends Collection interface and it provides a way to store the objects in a sequential order. It provides many methods so that we can perform different operations on it.
We can not create objects of an interface so we need derived-classes to create objects.So Java provided us 4 derived classesfor our use.They are :
The List interface contains various methods which is used to perform different Operations.
Methods | Description |
---|---|
add(element) | adds element at the end of the list |
add(int index, element) | adds an element at a particular index in the list. |
addAll(int index, Collection collection) | adds all the elements in the given collection to the list. |
size() | It returns the size of the list. |
clear() | It removes all the elements in the list. |
remove(int index) | It removes an element from the specified index. |
remove(element) | It removes the first occurrence of the given element in the list. |
get(int index) | It returns element at the specified index. |
set(int index, element) | It replaces element at given index with new element.It returns the element which was just replaced by new element. |
indexOf(element) | It returns the first occurrence of the given element or -1 if the element is not present in the list. |
lastIndexOf(element) | It returns the last occurrence of the given element or -1 if the element is not present in the list. |
equals(element) | It compares the equality of the given element with the elements of the list. |
hashcode() | It returns the hashcode value of the given list. |
isEmpty() | It checks if the list is empty or not. It returns true if the list is empty, else false. |
contains(element) | It checks if the list contains the given element or not. It returns true if the list contains the element. |
containsAll(Collection collection) | It checks if the list contains all the collection of elements. |
sort(Comparator comp) | It sorts the elements of the list on the basis of the given comparator. |