https://www.programiz.com/java-programming/list
https://www.tutorialspoint.com/java/java_list_interface.htm
https://www.w3schools.com/java/java_list.asp
https://www.geeksforgeeks.org/java/list-interface-java-examples/
List Interface
The List interface extends Collection and declares the behavior of a collection that stores a sequence of elements.
allows us to store and access elements sequentially.
Elements can be inserted or accessed by their position in the list, using a zero-based index.
In addition to the methods defined by Collection, List defines some of its own.
Several of the list methods will throw an UnsupportedOperationException if the collection cannot be modified, and a ClassCastException is generated when one object is incompatible with another.
part of the java.util package.
It is used to store ordered collections where duplicates are allowed and elements can be accessed by their index.
Maintains insertion order
Allows duplicate elements
Supports bidirectional traversal using ListIterator
The List interface is part of the Java Collections Framework and represents an ordered collection of elements.
You can access elements by their index, add duplicates, and maintain the insertion order.
Since List is an interface, you cannot create a List object directly.
Instead, you use a class that implements the List interface, such as:
Core Implementations
ArrayList - like a resizable array with fast random access. It provides fast O(1) random access but can be slow for insertions or deletions in the middle of the list.
LinkedList - Implements a doubly-linked list structure. It is highly efficient for frequent insertions and deletions but slower for random indexed access.like a train of cars you can easily attach or remove.
Vector: A synchronized, thread-safe dynamic array. It is slower than ArrayList due to synchronization overhead and is generally considered a legacy class.
Stack: A subclass of Vector that represents a Last-In-First-Out (LIFO) stack. Modern code bases typically favor ArrayDeque over Stack for LIFO operations.
ArrayList
Internal Structure: Dynamic Array
Thread Safety: Non-synchronized (Not safe)
Random Access (get):Fast (O(1))
Data Manipulation:Slow (requires element shifting)
LinkedList
Internal Structure: ArrayDoubly-Linked
Thread Safety: Non-synchronized (Not safe)
Random Access (get): Slow (O(n))
Data Manipulation:Fast (only pointer updates)
Vector
Internal Structure: Synchronized Dynamic Array
Thread Safety: Synchronized (Thread-safe)
Random Access (get):Fast (O(1))
Data Manipulation:Slow (requires element shifting)
Complexity of List Interface in Java
Operation: Adding Element in List Interface
Time Complexity:O(1)
Space Complexity:O(1)
Operation:Remove Element from List Interface
Time Complexity:O(N)
Space Complexity:O(1)
Operation:Replace Element in List Interface
Time Complexity:O(1)
Space Complexity:O(1)
Operation:Traversing List Interface
Time Complexity:O(N)
Space Complexity:O(1)
Use List when you care about order, you may have duplicates, and want to access elements by index.
Declaration of Java List Interface
public interface List<E> extends Collection<E>;
Creating a Java list
A Java list is created using the List interface. The syntax is as follows -
List<Obj> list = new ArrayList<Obj> ();
Example of List Interface
import java.util.*;
// The Main class
public class Main {
public static void main(String[] args) {
// Creating two lists using List interface
List < Integer > list1 = new ArrayList < Integer > ();
List < Integer > list2 = new ArrayList < Integer > ();
// Adding elements to list 1
list1.add(0, 10);
list1.add(1, 20);
// Printing list 1
System.out.println("list1 : " + list1);
// Adding elements to list 2
list2.add(10);
list2.add(20);
list2.add(30);
// Adding all elements of list 2 in list 1
list1.addAll(1, list2);
// Printing list 2
System.out.println("list2 : " + list2);
// Removes an element from list 1 (from index 1)
list1.remove(1);
// Printing list 1
System.out.println("list1 after removing an element: " + list1);
// get() method
System.out.println("list1 using get() : " + list1.get(2));
// Replacing element
list1.set(0, 50);
// Printing the list 1
System.out.println("list1 : " + list1);
}
}
Output
list1 : [10, 20]
list2 : [10, 20, 30]
list1 after removing an element: [10, 20, 30, 20]
list1 using get() : 30
list1 : [50, 20, 30, 20]
Common List Methods
Method Description
add() Adds an element to the end of the list
get() Returns the element at the specified position
set() Replaces the element at the specified position
remove() Removes the element at the specified position
size() Returns the number of elements in the list
List vs. Array
Array
Fixed size
Faster performance for raw data
Not part of Collections Framework
List
Dynamic size
More flexible and feature-rich
Part of the Collections Framework
Syntax
List<Type> list = new ArrayList<Type>();
import java.util.*;
class Geeks {
public static void main(String[] args)
{
// Creating a List of Strings using ArrayList
List<String> li = new ArrayList<>();
// Adding elements in List
li.add("Java");
li.add("Python");
li.add("DSA");
li.add("C++");
System.out.println("Elements of List are:");
// Iterating through the list
for (String s : li) {
System.out.println(s);
}
}
}
Output
Elements of List are:
Java
Python
DSA
C++
Java List - Operations
List can be used only with a class that implements this interface. how to perform a few frequently used operations on the List.
1. Adding Elements
To add an element to the list, we can use the add() method. This method is overloaded to perform multiple operations based on different parameters.
add(Object o): This method is used to add an element at the end of the List.
add(int index, Object o): This method is used to add an element at a specific index in the List
Example
import java.util.*;
class Geeks {
public static void main(String args[])
{
List<String> al = new ArrayList<>();
// Adding elements to object of List interface Custom elements
al.add("Geeks");
al.add("Geeks");
al.add(1, "For");
System.out.println(al);
}
}
Output
[Geeks, For, Geeks]
2. Updating Elements
To update an element in a list, use the set() method with the target index and the new value. Since List is indexed, the element is replaced at the specified position.
Example
import java.util.*;
class Geeks {
public static void main(String args[])
{
// Creating an object of List interface
List<String> al = new ArrayList<>();
// Adding elements to object of List class
al.add("Geeks");
al.add("Geeks");
al.add(1, "Geeks");
System.out.println("Initial ArrayList " + al);
// Setting (updating) element at 1st index using set() method
al.set(1, "For");
System.out.println("Updated ArrayList " + al);
}
}
Output
Initial ArrayList [Geeks, Geeks, Geeks]
Updated ArrayList [Geeks, For, Geeks]
3. Searching Elements
Searching in a List can be done using indexOf(), lastIndexOf() methods.
indexOf(Object o): It returns the index of the first occurrence of the specified element in the list or -1 if the element is not found
lastIndexOf(Object o): It returns the index of the last occurrence of the specified element in the list or -1 if the element is not found
import java.util.*;
class Geeks {
public static void main(String[] args)
{
// create a list of integers
List<Integer> al = new ArrayList<>();
// add some integers to the list
al.add(1);
al.add(2);
al.add(3);
al.add(2);
// use indexOf() to find the first occurrence of an element in the list
int i = al.indexOf(2);
System.out.println("First Occurrence of 2 is at Index: "+i);
// use lastIndexOf() to find the last occurrence of an element in the list
int l = al.lastIndexOf(2);
System.out.println("Last Occurrence of 2 is at Index: "+l);
}
}
Output
First Occurrence of 2 is at Index: 1
Last Occurrence of 2 is at Index: 3
4. Removing Elements
To remove an element from a list, we can use the remove() method. This method is overloaded to perform multiple operations based on different parameters.
remove(Object o): Removes the first occurrence of the specified object from the list.
remove(int index): Removes the element at the specified index and shifts subsequent elements left.
Example
import java.util.ArrayList;
import java.util.List;
class Geeks {
public static void main(String args[])
{
// Creating List class object
List<String> al = new ArrayList<>();
// Adding elements to the object Custom inputs
al.add("Geeks");
al.add("Geeks");
// Adding For at 1st indexes
al.add(1, "For");
System.out.println("Initial ArrayList " + al);
// Now remove element from the above list present at 1st index
al.remove(1);
System.out.println("After the Index Removal " + al);
// Now remove the current object from the updated List
al.remove("Geeks");
System.out.println("After the Object Removal " + al);
}
}
5. Accessing Elements
To access an element in the list, we can use the get() method, which returns the element at the specified index.
get(int index): This method returns the element at the specified index in the list.
Example
import java.util.*;
class Geeks {
public static void main(String args[])
{
List<String> al = new ArrayList<>();
// Adding elements to object of List interface
al.add("Geeks");
al.add("For");
al.add("Geeks");
// Accessing elements using get() method
String first = al.get(0);
String second = al.get(1);
String third = al.get(2);
System.out.println(first);
System.out.println(second);
System.out.println(third);
System.out.println(al);
}
}
Output
Geeks
For
Geeks
[Geeks, For, Geeks]
6. Checking if an element is present or not
To check if an element is present in the list, we can use the contains() method. This method returns true if the specified element is present in the list, otherwise, it returns false.
contains(Object o): This method takes a single parameter, the object to be checked if it is present in the list.
Example
import java.util.*;
class Geeks {
public static void main(String args[])
{
List<String> al = new ArrayList<>();
// Adding elements to object of List interface
al.add("Geeks");
al.add("For");
al.add("Geeks");
// Checking if element is present using contains() method
boolean isPresent = al.contains("Geeks");
// Printing the result
System.out.println("Is Geeks present in the list? "+ isPresent);
}
}
Output
Is Geeks present in the list? true
Iterating over List Interface in Java
For larger datasets, Lists can be iterated using:
Basic for loop with get(index)
Enhanced for-each loop
These methods allow efficient traversal of elements.
import java.util.*;
public class Geeks {
public static void main(String args[])
{
// Creating an empty Arraylist of string type
List<String> al = new ArrayList<>();
// Adding elements to above object of ArrayList
al.add("Geeks");
al.add("Geeks");
// Adding element at specified position inside list object
al.add(1, "For");
// Using for loop for iteration
for (int i = 0; i < al.size(); i++) {
// Using get() method to access particular element
System.out.print(al.get(i) + " ");
}
// New line for better readability
System.out.println();
// Using for-each loop for iteration
for (String str : al)
System.out.print(str + " ");
}
}
Output
Geeks For Geeks
Geeks For Geeks
Methods of the List Interface
add(int index, element)
This method is used with Java List Interface to add an element at a particular index in the list. When a single parameter is passed, it simply adds the element at the end of the list.
addAll(int index, Collection collection)
This method is used with List Interface in Java to add all the elements in the given collection to the list. When a single parameter is passed, it adds all the elements of the given collection at the end of the list.
size() This method is used with Java List Interface to return the size of the list.
clear() This method is used to remove all the elements in the list. However, the reference of the list created is still stored.
remove(int index) This method removes an element from the specified index. It shifts subsequent elements(if any) to left and decreases their indexes by 1.
remove(element) This method is used with Java List Interface to remove the first occurrence of the given element in the list.
get(int index) This method returns elements at the specified index.
set(int index, element) This method replaces elements at a given index with the new element. This function returns the element which was just replaced by a new element.
indexOf(element) This method returns the first occurrence of the given element or -1 if the element is not present in the list.
lastIndexOf(element) This method returns the last occurrence of the given element or -1 if the element is not present in the list.
equals(element) This method is used with Java List Interface to compare the equality of the given element with the elements of the list.
hashCode() This method is used with List Interface in Java to return the hashcode value of the given list.
isEmpty() This method is used with Java List Interface to check if the list is empty or not. It returns true if the list is empty, else false.
contains(element) This method is used with List Interface in Java to check if the list contains the given element or not. It returns true if the list contains the element.
containsAll(Collection collection) This method is used with Java List Interface to check if the list contains all the collection of elements.
sort(Comparator comp) This method is used with List Interface in Java to sort the elements of the list on the basis of the given comparator.
List vs Set
Both the List interface and the Set interface inherits the Collection interface. However, there exists some differences between them.
List
The List is an ordered sequence.
List allows duplicate elements
Elements by their position can be accessed.
Multiple null elements can be stored.
List implementations are ArrayList, LinkedList, Vector, Stack
Set
The Set is an unordered sequence.
Set doesn’t allow duplicate elements.
Position access to elements is not allowed.
The null element can store only once.
Set implementations are HashSet, LinkedHashSet.
In order to use the functionalities of the List interface, we can use these classes:
ArrayList
LinkedList
Vector
Stack
These classes are defined in the Collections framework and implement the List interface.
How to use List?
In Java, we must import java.util.List package in order to use List.
// ArrayList implementation of List
List<String> list1 = new ArrayList<>();
// LinkedList implementation of List
List<String> list2 = new LinkedList<>();
Here, we have created objects list1 and list2 of classes ArrayList and LinkedList. These objects can use the functionalities of the List interface.
The common implementation classes of the List interface are:
ArrayList: It is implemented using resizable array, offers fast random access but slower insert/delete.
LinkedList: It is implemented using Doubly-linked list, efficient for frequent insertions and deletions.
Methods of List
The List interface includes all the methods of the Collection interface. Its because Collection is a super interface of List.
Some of the commonly used methods of the Collection interface that's also available in the List interface are:
List Interface Methods
The following are the methods of List Interface in Java -
Sr.No. Method & Description
1
void add(int index, Object obj)
Inserts obj into the invoking list at the index passed in the index. Any pre-existing elements at or beyond the point of insertion are shifted up. Thus, no elements are overwritten.
2
boolean addAll(int index, Collection c)
Inserts all elements of c into the invoking list at the index passed in the index. Any pre-existing elements at or beyond the point of insertion are shifted up. Thus, no elements are overwritten. Returns true if the invoking list changes and returns false otherwise.
3
Object get(int index)
Returns the object stored at the specified index within the invoking collection.
4
int indexOf(Object obj)
Returns the index of the first instance of obj in the invoking list. If obj is not an element of the list, .1 is returned.
5
int lastIndexOf(Object obj)
Returns the index of the last instance of obj in the invoking list. If obj is not an element of the list, .1 is returned.
6
ListIterator listIterator( )
Returns an iterator to the start of the invoking list.
7
ListIterator listIterator(int index)
Returns an iterator to the invoking list that begins at the specified index.
8
Object remove(int index)
Removes the element at position index from the invoking list and returns the deleted element. The resulting list is compacted. That is, the indexes of subsequent elements are decremented by one.
9
Object set(int index, Object obj)
Assigns obj to the location specified by index within the invoking list.
10
List subList(int start, int end)
Returns a list that includes elements from start to end.1 in the invoking list. Elements in the returned list are also referenced by the invoking object.
More Examples of List Interface
Example: Java List using ArrayList
The above interface has been implemented using ArrayList. Following is the example to explain few methods from various class implementation of the above collection methods −
import java.util.ArrayList;
import java.util.List;
public class CollectionsDemo {
public static void main(String[] args) {
List<String> a1 = new ArrayList<>();
a1.add("Zara");
a1.add("Mahnaz");
a1.add("Ayan");
System.out.println(" ArrayList Elements");
System.out.print("\t" + a1);
}
}
Output
ArrayList Elements
[Zara, Mahnaz, Ayan]
Example: Java List using LinkedList
The above interface has been implemented using LinkedList. Following is the example to explain few methods from various class implementation of the above collection methods −
import java.util.LinkedList;
import java.util.List;
public class CollectionsDemo {
public static void main(String[] args) {
List<String> a1 = new LinkedList<>();
a1.add("Zara");
a1.add("Mahnaz");
a1.add("Ayan");
System.out.println(" LinkedList Elements");
System.out.print("\t" + a1);
}
}
Output
LinkedList Elements
[Zara, Mahnaz, Ayan]
Example: Adding Element to Java List
The above interface has been implemented using ArrayList. Following is another example to explain few methods from various class implementation of the above collection methods −
import java.util.ArrayList;
import java.util.List;
public class CollectionsDemo {
public static void main(String[] args) {
List<String> a1 = new ArrayList<>();
a1.add("Zara");
a1.add("Mahnaz");
a1.add("Ayan");
System.out.println(" ArrayList Elements");
System.out.print("\t" + a1);
// remove second element
a1.remove(1);
System.out.println("\n ArrayList Elements");
System.out.print("\t" + a1);
}
}
Output
ArrayList Elements
[Zara, Mahnaz, Ayan]
ArrayList Elements
[Zara, Ayan]
Top comments (0)