In Java, a List is an ordered collection of elements that allows duplicates and maintains the insertion order of the elements. It is one of the most commonly used data structures in Java and is available in the java.util package.
The List interface extends the Collection interface and defines the behavior of a collection that stores a sequence of elements. Some of the most commonly used methods of the List interface are:
- add(element) – adds an element to the end of the list
- add(index, element) – inserts an element at the specified position in the list
- get(index) – returns the element at the specified position in the list
- set(index, element) – replaces the element at the specified position in the list with the specified element
- remove(index) – removes the element at the specified position in the list
- size() – returns the number of elements in the list
- indexOf(element) – returns the index of the first occurrence of the specified element in the list
- contains(element) – returns true if the list contains the specified element
There are several implementations of the List interface in Java, including ArrayList, LinkedList, Vector, and Stack. Each implementation has its own strengths and weaknesses and can be used based on the specific requirements of the application.
List Interface declaration:
In Java, the List interface is declared in the java.util package. The declaration of the List interface is as follows:
public interface List<E> extends Collection<E> { // Query Operations int size(); boolean isEmpty(); boolean contains(Object o); Iterator<E> iterator(); Object[] toArray(); <T> T[] toArray(T[] a); // Modification Operations boolean add(E e); boolean remove(Object o); // Bulk Modification Operations boolean containsAll(Collection<?> c); boolean addAll(Collection<? extends E> c); boolean addAll(int index, Collection<? extends E> c); boolean removeAll(Collection<?> c); boolean retainAll(Collection<?> c); void clear(); // Comparison and hashing boolean equals(Object o); int hashCode(); // Positional Access Operations E get(int index); E set(int index, E element); void add(int index, E element); E remove(int index); // Search Operations int indexOf(Object o); int lastIndexOf(Object o); // List Iterators ListIterator<E> listIterator(); ListIterator<E> listIterator(int index); // View Operations List<E> subList(int fromIndex, int toIndex); }
The List interface extends the Collection interface and adds methods for accessing elements based on their index, searching for elements, and iterating over the elements in the list. It also includes methods for bulk modification operations such as adding, removing, and replacing elements, as well as methods for creating sublists of the original list.
Java List Methods:
In Java, the List interface defines several methods that can be used to manipulate the elements of a list. Here is a list of some of the most commonly used methods:
add(E element)
: Adds the specified element to the end of the list.
List<String> list = new ArrayList<>(); list.add("apple"); list.add("banana");
add(int index, E element)
: Inserts the specified element at the specified position in the list.
List<String> list = new ArrayList<>(); list.add("apple"); list.add(1, "banana");
get(int index)
: Returns the element at the specified position in the list.
List<String> list = new ArrayList<>(); list.add("apple"); list.add("banana"); String fruit = list.get(1); // returns "banana"
set(int index, E element)
: Replaces the element at the specified position in the list with the specified element.
List<String> list = new ArrayList<>(); list.add("apple"); list.add("banana"); list.set(1, "orange");
remove(int index)
: Removes the element at the specified position in the list.
List<String> list = new ArrayList<>(); list.add("apple"); list.add("banana"); list.remove(1);
size()
: Returns the number of elements in the list.
List<String> list = new ArrayList<>(); list.add("apple"); list.add("banana"); int size = list.size(); // returns 2
indexOf(Object o)
: Returns the index of the first occurrence of the specified element in the list, or -1 if the list does not contain the element.
List<String> list = new ArrayList<>(); list.add("apple"); list.add("banana"); int index = list.indexOf("banana"); // returns 1
contains(Object o)
: Returns true if the list contains the specified element, otherwise false.
List<String> list = new ArrayList<>(); list.add("apple"); list.add("banana"); boolean contains = list.contains("banana"); // returns true
addAll(Collection<? extends E> c)
: Adds all of the elements in the specified collection to the end of the list.
List<String> list = new ArrayList<>(); list.add("apple"); list.add("banana"); List<String> fruits = new ArrayList<>(); fruits.add("orange"); fruits.add("mango"); list.addAll(fruits); // adds "orange" and "mango" to the end of the list
subList(int fromIndex, int toIndex)
: Returns a view of the portion of the list between the specified fromIndex, inclusive, and toIndex, exclusive.
List<String> list = new ArrayList<>(); list.add("apple"); list.add("banana"); list.add("orange"); List<String> sublist = list.subList(1, 3); // returns ["banana", "orange"]
These are just a few of the methods available in the List interface. There are many more methods available for manipulating and querying lists, including methods for sorting, shuffling, and iterating over lists.
Java List vs ArrayList:
In Java, the List interface is a generic interface that defines the behavior of a list, while ArrayList is a specific implementation of the List interface. Here are some of the key differences between List and ArrayList:
- Interface vs. Class: List is an interface, which means that it defines a set of methods that a class must implement, while ArrayList is a class that implements the List interface.
- Resizing: ArrayList is a resizable array implementation of the List interface, which means that it can dynamically resize itself to accommodate new elements. List interface itself does not specify how elements are stored or how resizing is implemented.
- Access time: ArrayList provides constant-time access to elements, while accessing elements in other types of List implementations, such as LinkedList, may require traversing the list.
- Memory: ArrayList is not memory-efficient as it requires contiguous memory allocation for storing its elements. Other types of List implementations may use less memory by storing elements in separate nodes.
- Synchronization: ArrayList is not synchronized by default, which means that it is not thread-safe. If multiple threads access an ArrayList concurrently and at least one of the threads modifies the list structurally, it must be synchronized externally. The List interface itself does not specify whether an implementation is synchronized or not.
In general, the choice between List and ArrayList depends on the specific requirements of the program. If constant-time access to elements is important and memory usage is not a concern, ArrayList may be the best choice. However, if memory usage is a concern or frequent insertion and deletion operations are required, a different implementation of the List interface, such as LinkedList, may be more appropriate.
How to create List:
In Java, you can create a List by using one of the many implementations of the List interface provided by the Java Collections Framework. Here are some of the ways to create a List in Java:
- ArrayList: This is one of the most commonly used implementations of the List interface in Java. To create an ArrayList, you can use the following code:
List<String> list = new ArrayList<>();
- LinkedList: This implementation of the List interface uses a doubly linked list to store its elements. To create a LinkedList, you can use the following code:
List<String> list = new LinkedList<>();
- Vector: This is a synchronized implementation of the List interface. To create a Vector, you can use the following code:
List<String> list = new Vector<>();
- Stack: This is another synchronized implementation of the List interface that extends Vector. To create a Stack, you can use the following code:
Stack<String> stack = new Stack<>();
- Arrays.asList(): This method allows you to create a List from an array. To create a List from an array, you can use the following code:
String[] array = {"apple", "banana", "orange"}; List<String> list = Arrays.asList(array);
- List.of(): This method was introduced in Java 9 and allows you to create an immutable List. To create an immutable List, you can use the following code:
List<String> list = List.of("apple", "banana", "orange");
Note that in the above examples, the type parameter <String>
specifies the type of the elements that the list will contain. You can replace <String>
with any other class or interface to create a list of elements of that type.
Java List Example:
Sure, here is an example of how to use a List in Java:
import java.util.ArrayList; import java.util.List; public class ListExample { public static void main(String[] args) { // Creating a List of Strings using ArrayList List<String> fruits = new ArrayList<>(); // Adding elements to the List fruits.add("Apple"); fruits.add("Banana"); fruits.add("Cherry"); fruits.add("Dates"); // Accessing elements of the List System.out.println("The first fruit in the list is: " + fruits.get(0)); // Iterating over the List using a for loop System.out.println("The elements of the list are: "); for (int i = 0; i < fruits.size(); i++) { System.out.println(fruits.get(i)); } // Iterating over the List using a for-each loop System.out.println("The elements of the list are: "); for (String fruit : fruits) { System.out.println(fruit); } // Removing an element from the List fruits.remove("Banana"); System.out.println("The elements of the list after removing Banana are: "); for (String fruit : fruits) { System.out.println(fruit); } } }
In this example, we first create a List of Strings using the ArrayList implementation. We then add four elements to the list using the add()
method. We access the first element of the list using the get()
method and print it to the console.
We then iterate over the list using both a for loop and a for-each loop and print each element to the console. We then remove an element from the list using the remove()
method and iterate over the updated list to print the remaining elements to the console.
How to convert Array to List:
In Java, you can convert an array to a List by using the Arrays.asList()
method. This method returns a fixed-size List that is backed by the original array, which means that any changes made to the List will be reflected in the original array. Here is an example:
import java.util.Arrays; import java.util.List; public class ArrayToListExample { public static void main(String[] args) { String[] fruitsArray = {"Apple", "Banana", "Cherry", "Dates"}; // Converting an array to a List List<String> fruitsList = Arrays.asList(fruitsArray); // Printing the List System.out.println("The elements of the List are:"); for (String fruit : fruitsList) { System.out.println(fruit); } } }
In this example, we first create an array of Strings called fruitsArray
with four elements. We then use the Arrays.asList()
method to convert the array to a List and store it in a variable called fruitsList
. Finally, we iterate over the List using a for-each loop and print each element to the console.
Note that since the List returned by Arrays.asList()
is a fixed-size List, you cannot add or remove elements from it. If you want to create a mutable List from an array, you should create a new ArrayList and add the elements from the array to it, like this:
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class ArrayToListExample2 { public static void main(String[] args) { String[] fruitsArray = {"Apple", "Banana", "Cherry", "Dates"}; // Converting an array to a mutable List List<String> fruitsList = new ArrayList<>(Arrays.asList(fruitsArray)); // Adding an element to the List fruitsList.add("Elderberry"); // Printing the List System.out.println("The elements of the List are:"); for (String fruit : fruitsList) { System.out.println(fruit); } } }
In this example, we first create an array of Strings called fruitsArray
with four elements. We then use the Arrays.asList()
method to create a fixed-size List from the array, and then pass that List to the constructor of a new ArrayList. This creates a mutable List that contains the same elements as the original array. We then add a new element to the List using the add()
method, and finally iterate over the List and print each element to the console.
How to convert List to Array:
In Java, you can convert a List to an array by using the toArray()
method. This method returns an array that contains all of the elements in the List, in the same order as they appear in the List. Here is an example:
import java.util.ArrayList; import java.util.List; public class ListToArrayExample { public static void main(String[] args) { List<String> fruitsList = new ArrayList<>(); fruitsList.add("Apple"); fruitsList.add("Banana"); fruitsList.add("Cherry"); fruitsList.add("Dates"); // Converting a List to an array String[] fruitsArray = fruitsList.toArray(new String[fruitsList.size()]); // Printing the array System.out.println("The elements of the array are:"); for (String fruit : fruitsArray) { System.out.println(fruit); } } }
In this example, we first create a List of Strings called fruitsList
and add four elements to it using the add()
method. We then use the toArray()
method to convert the List to an array and store it in a variable called fruitsArray
. The argument to the toArray()
method is a new array of the same type as the List, with a length equal to the size of the List. This tells the toArray()
method what type of array to create and how many elements to copy into it.
Finally, we iterate over the array using a for-each loop and print each element to the console.
Note that the toArray()
method returns an array of type Object[]
if you don’t specify a type argument, so you should always specify a type argument when calling this method if you want to get an array of a specific type.
Get and Set Element in List:
In Java, you can get and set elements in a List by using the get()
and set()
methods, respectively.
The get()
method retrieves the element at a specified index in the List. The index of the first element in the List is 0. Here is an example:
import java.util.ArrayList; import java.util.List; public class GetElementInListExample { public static void main(String[] args) { List<String> fruitsList = new ArrayList<>(); fruitsList.add("Apple"); fruitsList.add("Banana"); fruitsList.add("Cherry"); fruitsList.add("Dates"); // Getting an element from the List String fruit = fruitsList.get(1); // Printing the element System.out.println("The element at index 1 is: " + fruit); } }
In this example, we first create a List of Strings called fruitsList
and add four elements to it using the add()
method. We then use the get()
method to retrieve the element at index 1 (which is the second element) and store it in a variable called fruit
. Finally, we print the element to the console.
The set()
method replaces the element at a specified index in the List with a new element. Here is an example:
import java.util.ArrayList; import java.util.List; public class SetElementInListExample { public static void main(String[] args) { List<String> fruitsList = new ArrayList<>(); fruitsList.add("Apple"); fruitsList.add("Banana"); fruitsList.add("Cherry"); fruitsList.add("Dates"); // Setting an element in the List fruitsList.set(2, "Elderberry"); // Printing the List System.out.println("The elements of the List are:"); for (String fruit : fruitsList) { System.out.println(fruit); } } }
In this example, we first create a List of Strings called fruitsList
and add four elements to it using the add()
method. We then use the set()
method to replace the element at index 2 (which is the third element) with the String “Elderberry”. Finally, we iterate over the List using a for-each loop and print each element to the console.
Note that the set()
method throws an IndexOutOfBoundsException
if the index is out of range (i.e., less than 0 or greater than or equal to the size of the List).
How to Sort List:
In Java, you can sort a List using the sort()
method provided by the Collections
class. The sort()
method sorts the elements of the List in ascending order, according to their natural ordering (i.e., the ordering defined by the compareTo()
method of the elements’ class) or using a custom comparator.
Here is an example of sorting a List of Strings:
import java.util.ArrayList; import java.util.Collections; import java.util.List; public class SortListExample { public static void main(String[] args) { List<String> fruitsList = new ArrayList<>(); fruitsList.add("Banana"); fruitsList.add("Apple"); fruitsList.add("Cherry"); fruitsList.add("Dates"); // Sorting the List Collections.sort(fruitsList); // Printing the sorted List System.out.println("The sorted List is:"); for (String fruit : fruitsList) { System.out.println(fruit); } } }
In this example, we first create a List of Strings called fruitsList
and add four elements to it using the add()
method. We then use the sort()
method of the Collections
class to sort the List in ascending order. Finally, we iterate over the sorted List using a for-each loop and print each element to the console.
Note that the sort()
method modifies the original List, so if you want to preserve the original order of the List, you should create a copy of it before sorting it.
You can also use a custom comparator to sort the List in a different order. Here is an example of sorting a List of Integers in descending order:
import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class SortListDescendingOrderExample { public static void main(String[] args) { List<Integer> numbersList = new ArrayList<>(); numbersList.add(5); numbersList.add(1); numbersList.add(9); numbersList.add(3); // Sorting the List in descending order using a custom comparator Comparator<Integer> descendingOrderComparator = Collections.reverseOrder(); Collections.sort(numbersList, descendingOrderComparator); // Printing the sorted List System.out.println("The sorted List in descending order is:"); for (Integer number : numbersList) { System.out.println(number); } } }
In this example, we first create a List of Integers called numbersList
and add four elements to it using the add()
method. We then create a custom comparator using the reverseOrder()
method of the Collections
class, which sorts the elements in descending order. Finally, we use the sort()
method of the Collections
class with the custom comparator to sort the List in descending order, and print the sorted List to the console.
Java ListIterator Interface:
The ListIterator
interface in Java provides a way to iterate over a List
in both forward and backward directions, and allows you to modify the List during iteration. The ListIterator
interface extends the Iterator
interface and adds additional methods for these functionalities.
Here is an example of using ListIterator
to iterate over a List
in both directions:
import java.util.ArrayList; import java.util.List; import java.util.ListIterator; public class ListIteratorExample { public static void main(String[] args) { List<String> fruitsList = new ArrayList<>(); fruitsList.add("Apple"); fruitsList.add("Banana"); fruitsList.add("Cherry"); // Creating a ListIterator for the List ListIterator<String> listIterator = fruitsList.listIterator(); // Iterating over the List in forward direction System.out.println("Iterating in forward direction:"); while (listIterator.hasNext()) { String fruit = listIterator.next(); System.out.println(fruit); } // Iterating over the List in backward direction System.out.println("Iterating in backward direction:"); while (listIterator.hasPrevious()) { String fruit = listIterator.previous(); System.out.println(fruit); } } }
In this example, we first create a List
called fruitsList
and add three elements to it using the add()
method. We then create a ListIterator
for the List using the listIterator()
method of the List
interface. We can then use the hasNext()
and next()
methods of the ListIterator
to iterate over the List in forward direction, and the hasPrevious()
and previous()
methods to iterate over the List in backward direction.
Note that the ListIterator
interface also provides methods for adding, setting and removing elements during iteration, such as add()
, set()
and remove()
. These methods can be used to modify the List while iterating over it.
ListIterator Interface declaration:
The ListIterator
interface in Java is a subinterface of the Iterator
interface, and provides additional functionality for iterating over a List
in both forward and backward directions, and modifying the List during iteration. The declaration of the ListIterator
interface is as follows:
public interface ListIterator<E> extends Iterator<E> { boolean hasNext(); E next(); boolean hasPrevious(); E previous(); int nextIndex(); int previousIndex(); void remove(); void set(E e); void add(E e); }
The ListIterator
interface extends the Iterator
interface and adds the following additional methods:
hasPrevious()
: Returnstrue
if there is a previous element in the List that can be returned by theprevious()
method.previous()
: Returns the previous element in the List and moves the iterator position backwards by one.nextIndex()
: Returns the index of the element that would be returned by a subsequent call to thenext()
method.previousIndex()
: Returns the index of the element that would be returned by a subsequent call to theprevious()
method.remove()
: Removes the last element returned by thenext()
orprevious()
method from the List. This method can only be called once per call tonext()
orprevious()
.set(E e)
: Replaces the last element returned by thenext()
orprevious()
method with the specified element.add(E e)
: Inserts the specified element into the List immediately before the next element that would be returned by thenext()
method.
Note that the ListIterator
interface is only implemented by classes that implement the List
interface, such as ArrayList
and LinkedList
.
Methods of Java ListIterator Interface:
The ListIterator
interface in Java is a subinterface of the Iterator
interface, and provides additional functionality for iterating over a List
in both forward and backward directions, and modifying the List during iteration. The following are the methods provided by the ListIterator
interface:
hasNext()
: Returnstrue
if there is a next element in the List that can be returned by thenext()
method, otherwise returnsfalse
.next()
: Returns the next element in the List and moves the iterator position forward by one.hasPrevious()
: Returnstrue
if there is a previous element in the List that can be returned by theprevious()
method, otherwise returnsfalse
.previous()
: Returns the previous element in the List and moves the iterator position backward by one.nextIndex()
: Returns the index of the element that would be returned by a subsequent call to thenext()
method.previousIndex()
: Returns the index of the element that would be returned by a subsequent call to theprevious()
method.remove()
: Removes the last element returned by thenext()
orprevious()
method from the List. This method can only be called once per call tonext()
orprevious()
.set(E e)
: Replaces the last element returned by thenext()
orprevious()
method with the specified element.add(E e)
: Inserts the specified element into the List immediately before the next element that would be returned by thenext()
method.
Note that the ListIterator
interface is only implemented by classes that implement the List
interface, such as ArrayList
and LinkedList
.
Example of ListIterator Interface:
Here’s an example of using the ListIterator
interface to iterate over a List
and modify its elements:
import java.util.ArrayList; import java.util.ListIterator; public class ListIteratorExample { public static void main(String[] args) { ArrayList<String> list = new ArrayList<String>(); list.add("Java"); list.add("Python"); list.add("C++"); list.add("JavaScript"); ListIterator<String> iterator = list.listIterator(); // Iterate over the List in forward direction System.out.println("List elements in forward direction:"); while (iterator.hasNext()) { String element = iterator.next(); System.out.println(element); } // Iterate over the List in backward direction System.out.println("\nList elements in backward direction:"); while (iterator.hasPrevious()) { String element = iterator.previous(); System.out.println(element); } // Modify List elements while iterating System.out.println("\nModified List elements:"); while (iterator.hasNext()) { String element = iterator.next(); if (element.equals("C++")) { iterator.set("Ruby"); } else if (element.equals("JavaScript")) { iterator.add("TypeScript"); } else if (element.equals("Java")) { iterator.remove(); } } // Iterate over the modified List System.out.println("\nList elements after modification:"); for (String element : list) { System.out.println(element); } } }
Output:
List elements in forward direction: Java Python C++ JavaScript List elements in backward direction: JavaScript C++ Python Java Modified List elements: Ruby Python TypeScript List elements after modification: Ruby Python TypeScript
In the above example, we create an ArrayList
and add some elements to it. We then create a ListIterator
object and use it to iterate over the List in both forward and backward directions. We also modify the List elements while iterating using the set()
and add()
methods of the ListIterator
interface. Finally, we iterate over the modified List using a for-each
loop to print its elements.
Example of List: Book
Here’s an example of using a List
to store and manipulate a list of Book
objects:
import java.util.ArrayList; import java.util.List; public class Book { private String title; private String author; public Book(String title, String author) { this.title = title; this.author = author; } public String getTitle() { return title; } public String getAuthor() { return author; } public static void main(String[] args) { List<Book> books = new ArrayList<Book>(); books.add(new Book("Java for Beginners", "John Smith")); books.add(new Book("Python Programming", "Emily Davis")); books.add(new Book("Web Development with JavaScript", "Michael Johnson")); // Print the list of books System.out.println("List of books:"); for (Book book : books) { System.out.println(book.getTitle() + " by " + book.getAuthor()); } // Add a new book to the list books.add(new Book("Data Science Essentials", "Laura Lee")); // Remove a book from the list books.remove(1); // Update the author of a book books.get(0).author = "John Doe"; // Print the updated list of books System.out.println("\nUpdated list of books:"); for (Book book : books) { System.out.println(book.getTitle() + " by " + book.getAuthor()); } } }
Output:
List of books: Java for Beginners by John Smith Python Programming by Emily Davis Web Development with JavaScript by Michael Johnson Updated list of books: Java for Beginners by John Doe Web Development with JavaScript by Michael Johnson Data Science Essentials by Laura Lee
In the above example, we define a Book
class with two attributes title
and author
. We then create a List
of Book
objects and add some books to it. We print the list of books using a for-each
loop. We then add a new book to the list, remove a book from the list, and update the author of a book using the add()
, remove()
, and get()
methods of the List
interface, respectively. Finally, we print the updated list of books using a for-each
loop.