Java List interface
A list in java represents a collection which is ordered.
Ordered means it maintains the order of insertion, elements are inserted at an index and can be retrieved using their index or position.
Index is numeric value which begins at 0.
So, the first element of list has 0 index, second has 1 index and the last element of the list has an index equal to one less than total number number of elements.
Below illustration depicts the position of list interface in java collection framework
Java list creation
List is an interface and resides in
java.util
package. Since it is an interface, its object or instance can not be created.
For creating a list, we can use any of its implementation classes such as
- ArrayList
- LinkedList
- Vector
- Stack(indirect implementation)
- CopyOnWriteArrayList
Following are the examples in which a list can be created using these implementation classes
// array list implementation List<String> names = new ArrayList<>(); // linked list implementation List<Integer> integers = new LinkedList<>(); // vector implementation List<Double> numbers = new Vector<>(); // stack implementation List<String> stack = new Stack<>();
Java List features
- Java list is an ordered collection. Elements maintain insertion order.
- Elements of java list can be accessed and inserted using index.
- Java list allows duplicate elements.
- Java list allows null elements. This also depends on list implementations.
- Java list is a generic interface. This means that it can hold elements of different types.
Important List interface methods
Following are commonly used methods declared in list interface. All list implementation classes must provide implementations of these methods.
1. add(E)
Adds the element supplied as argument to the end of list.
This method throws
UnsupportedOperationException
if the list implementation does not support addition.ClassCastException
, if the type of added element is incompatible with the type of list.- NullPointerException, if the element is
null
and list implementation does not allownull
values.
2. addAll(Collection)
Adds all the elements of the supplied collection argument to the end of this list.
Throws
UnsupportedOperationException
if the list implementation does not support addition.ClassCastException
, if the type of added element is incompatible with the type of list.- NullPointerException, if the element is
null
and list implementation does not allownull
values. IllegalArgumentException
if some property of the supplied argument does not allow adding it to the list.
3. contains(Object)
Returns true if any element of the list matches the supplied argument element. Elements are compared and should match as per equals() method.
Throws
ClassCastException
, if the type of added element is incompatible with the type of list.- NullPointerException, if the element is
null
and list implementation does not allownull
values.
4. get(int)
Returns the element at the supplied index.
Throws,
IndexOutOfBoundsException
, if the index is less than 0 or greater than the size of list.
5. indexOf(Object)
Returns the index of first element from the list which matches the supplied argument element. Elements are compared and should match as per equals()
method.
If the element is not present, -1 is returned.
Throws
ClassCastException
, if the type of added element is incompatible with the type of list.NullPointerException
, if the element isnull
and list implementation does not allownull
values.
6. iterator()
Returns an iterator to loop over the elements of the list.
7. listIterator()
Returns an object of ListIterator interface for iterating over list elements.
This is a special iterator that can loop a list in forward and reverse directions, get the index of current position and also add and remove list elements during iteration.
7. remove(E)
Removes the first element from the list which matches the supplied argument element. Elements are compared and should match as per equals()
method.
Throws
UnsupportedOperationException
if the list implementation does not support addition.ClassCastException
, if the type of added element is incompatible with the type of list.- NullPointerException, if the element is
null
and list implementation does not allownull
values.
8. remove(index)
It removes the element at the specified index. All the elements are shifted to the left.
Returns the element that was removed.
Throws
UnsupportedOperationException
if the list implementation does not support addition.IndexOutOfBoundsException
, if the index is less than 0 or greater than the size of list.
9. set(int, E)
Replaces the element at the index with the supplied argument element.
Returns existing element at that index.
Throws,
UnsupportedOperationException
if the list implementation does not support updating values.ClassCastException
, if the type of added element is incompatible with the type of list.NullPointerException
, if the element isnull
and list implementation does not allownull
values.IllegalArgumentException
, if some property of the supplied argument does not allow adding it to the list.
Below is a code snippet that uses
ArrayList
implementation of List
interface to show its usage.
// create a list List<String> names = new ArrayList<>(); // add elements names.add("Abc"); names.add("Def"); names.add("Ghi"); // get name at second position String name = names.get(1); System.out.println("Second name is: " + name); // check if list has value boolean contains = names.contains("Ghi"); System.out.println("List contains name: " + contains); contains = names.contains("Xyz"); System.out.println("List contains name: " + contains); // update third name names.set(2, "Jkl"); // get third name name = names.get(2); System.out.println("Third name is: " + name); // get size int size = names.size(); System.out.println("List size : " + size); // remove element String removed = names.remove(2); System.out.println("Element removed is : " + removed); // get size again size = names.size(); System.out.println("List size : " + size);
Below is the output
Second name is: Def
List contains name: true
List contains name: false
Third name is: Jkl
List size : 3
Element removed is : Jkl
List size : 2
List.of() java 9
In java 9, a new of()
method has been added to List
interface. This is a static interface method which creates and returns a list.
There are overloaded versions of this method, which accept multiple elements as arguments and return a list with these values added to it. Example,
List<Object> empty = List.of(); System.out.println("List empty: " + empty.isEmpty()); List<String> names = List.of("A", "B", "C"); System.out.println("List size: "+names.size());
Output is
List empty: true
List size: 3
Any number of arguments can be supplied to of()
, since there is an overloaded variant of this method which accepts variable arguments(or var args).
List returned by of()
can not be modified, meaning that you can not add or remove elements from it.
Trying to do so would result in UnsupportedOperationException
as explained in this article.
Java List vs Set
Following are the similarities between a java list and set interfaces.
- Both store elements in a linear(or one dimensional) format.
- Both extend
java.util.Collection
interface.
Following are the differences
- List allows duplicate elements while set does not.
- List is ordered while set is unordered.
This means that list elements are arranged in the order of insertion while set does not maintain any such order. - List allows element insertion, removal and retrieval using its index.
In set, elements can not be added, removed or retrieved using index. - List provides a java iterator and a special iterator,
ListIterator
to loop through list elements.
Set only provides java iterator, there is no additional iterators.