List Interface in Java


Java Java List ListViews 2579

List Interface in Java

A Java list or List Interface in Java is a collection or sequence of elements in an ordered manner. Since the list maintains a particular sequence, we can perform any operation like add, delete, get, set on the list using the required index. The index always starts at 0. It extends the Collection interface.

Java List Class or Interface?

The list is an interface and not a class. So we must always say List Interface.

Java List Interface (List Syntax)

We can create a List Interface in the below ways. We can use either ArrayList(), LinkedList() or Stack.

Without object type

We can store any type of value in List if we do not specify the object type.

List listname = new ArrayList();

With object type

We can store only specific value type in List if we specify the object type.

List<ObjType> listname = new ArrayList<ObjType>();

Eg: List<String> listname = new ArrayList<String>(); –> The list can store only String values

Restrict list item count

List<ObjType> listname = new ArrayList<ObjType>(number);

Eg: List<String> listname = new ArrayList<String>(2); –> The list can store only 2 values

Package to import

We need to import the below mentioned package in order to use the Java list interface.

import java.util.List;

Java List Exceptions

Java List Interface throws below exceptions:

  • UnsupportedOperationException – when the operation is not supported
  • IndexOutofBoundsException – when invalid index is specified (fromIndex<0 or fromIndex> toIndex or toIndex>size)
  • ClassCastException – when the class of the specified element prevents to add it to the list
  • NullPointerException – when the specified element is null and the list does not allow to add null elements
  • IllegalArgumentException – when some property of the element prevents to add to the list

Java List Methods

Java List Interface supports all the below-mentioned methods along with default methods of the Collection interface.

MethodDescriptionParameter
Boolean add(Object e)Adds the specified element to the end of list.e - the element to be added.
Return value - True
void add(int index, Object e)Adds the element to the specified index. If the index already contains an element, it is shifted to the rightindex- the index at which the element needs to be inserted
e - the element which needs to be inserted
Boolean addAll(Collection c)Adds a collection of specified elements to the list.c - collection of elements to be added
Return value - true
Boolean addAll(int index, Collection c)Adds a collection of elements at the specified index. If the index already contains element, it is subsequently shifted to the rightindex - index at which the elements needs to be added
c - collection of elements to be added
Return value - True
void clear()Clears all the elements in the list.
Boolean contains(Object o)Checks if the list contains the specified elementReturn value - true if the list contains the element
Boolean containsAll(Collection c)Checks if the list contains all the elements in the collectionReturn value - true if the list contains all the elements
Boolean equals(Object o)Compares if the list contains all the specified elements in the exact orderReturn value - true if object elements match with the list
Object getIndex(int index)Retrieves the element at the specified indexindex - the index at which the element that needs to be retrieved
Return value - The element at the specified index
int indexOf(Object o)Fetches the index of the first occurrence of the specified elemento - The element to be identified
Return value - index value
Boolean isEmpty()Checks if the list is empty or notReturn value - true if list contains no values
Iterator iterator()Retrieves the iterator of list in sequenceReturn value - Iterator
int lastIndexOf(Object o)Retrieves the last occurrence of the specified objecto - Element to be identified
Return value - index value
Object remove(int index)Removes the element at the specified indexindex - index position at which the element has to be removed
Return value - The element that is removed
Boolean remove(Object o)Removes the first occurrence of the specified object from the list if presento - The element that needs to be removed
Return value - true if list contains the element
Boolean removeAll(Collection c)Removes the first occurrence of all the elements in the collection from the list if presentc - collection of elements
Return value - true if the list contains the collection
Boolean retainAll(Collection c)Retains all the elements specified in collection in list. Other elements will be removedc - collection of elements that has to be retained
Return value - true if the list changed due to the method called
Object set(int index, Object o)Replaces the element at the specified index with the object passedo - the element to be replaced
index - index of the element
Return value - Returns the element which was previously at the specified index
int size()Fetches the size of the listReturn value - size of the list
List sublist(int fromIndex, int toIndex)Retrieves the part of the list based on start and endIndexfromIndex - position from which the sublist has to be retrieved (included)
toIndex - the index until which the sublist has to be retrieved (excluded)

Java List Example

Program to illustrate list() operations

import java.util.ArrayList;
import java.util.List;

public class ListExample {

  public static void main(String[] args) {
    List<String> list1 = new ArrayList<String>();
    //Add elements to List1
    list1.add("Java");
    list1.add("Javascript");
    list1.add("C#");
    System.out.println("Elements of List1");
    System.out.println(list1);
    
    //Add element at index1
    list1.add(1, "C");
    System.out.println("Elements of List1 after adding new element at index 1:");
    System.out.println(list1);
    
    //Create new List with elements
    List<String> list2 = new ArrayList<String>();
    list2.add("PHP");
    list2.add("C++");
    System.out.println("Elements of List2");
    System.out.println(list2);
    
    //Adds all elements from List2 to List1
    list1.addAll(1, list2);
    System.out.println("Elements of List 1 after adding List2 elements");
    System.out.println(list1);
    
    //Fetch sublist from List1
    List<String> sub = new ArrayList<String>();
    sub = list1.subList(1, 3);
    System.out.println("Sublist of List 1 from index 1 to 3:" + sub);
    
    //Check if List1 contains an element
    Boolean b = list1.contains("C");
    System.out.println("To check if List1 contains C : " + b);
    
    //Check if List1 contains a collection
    b = list1.containsAll(list2);
    System.out.println("To check if List1 contains List2 elements : " + b);
    
    //Get an element of specific index
    String strvalue = list1.get(4);
    System.out.println("Element at index 4: " + strvalue);
    
    //Set an element at specific index
    list2.set(1, "VBScript");
    System.out.println("Elements in List2 after setting an element at index 1");
    System.out.println(list2);
    
    //Get list size
    System.out.println("Size of List2 is : " + list2.size());
    
    //Remove an element at specific index
    String strval = list1.remove(1);
    System.out.println("The element " + strval + " is removed from List1");
    System.out.println("Elements in List1 after remove method:");
    System.out.println(list1);
  }
}
Output:
Elements of List1
[Java, Javascript, C#]
Elements of List1 after adding new element at index 1:
[Java, C, Javascript, C#]
Elements of List2
[PHP, C++]
Elements of List 1 after adding List2 elements
[Java, PHP, C++, C, Javascript, C#]
Sublist of List 1 from index 1 to 3:[PHP, C++]
To check if List1 contains C : true
To check if List1 contains List2 elements : true
Element at index 4: Javascript
Elements in List2 after setting an element at index 1
[PHP, VBScript]
Size of List2 is : 2
The element PHP is removed from List1
Elements in List1 after remove method:
[Java, C++, C, Javascript, C#]

ListIterator

We use ListIterator to iterate or traverse through the list. It is an extension of the Iterator interface and supports the below operations.

MethodDescription
Boolean hasNext()Returns True if list has next value. It is used to check if the list has more values to traverse in forward direction
String next()Returns the next element
void remove()Removes the last element which was returned by next() or previous(). It can be called only once per each call
Boolean hasPrevious()Returns true if the list has more values while iterating in reverse direction
int nextIndex()Returns the index of the element returned by next
() method
String previous()Returns the previous element in the list
int previousIndex()Returns the index of the element returned by previous() method
void set(String e)Replaces the element returned by next() or previous() with the value passed

ListIterator Exceptions

ListIterator throws the below exceptions:

  • ConcurrentModificationException – when we try to modify the list while traversing
  • NoSuchElementException – when there is no such element to be returned by the iterator.

Example: Java program to illustrate ListIterator

import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

public class IteratorExample {

  public static void main(String[] args) {
    ListIterator<String> litr = null;
      List<String> months = new ArrayList<String>();
      months.add("Jan");
      months.add("Feb");
      months.add("March");
      months.add("April");
      months.add("May");
      
      //Obtaining list iterator
      litr=months.listIterator();
   
      System.out.println("Navigating the list in forward direction:");
      while(litr.hasNext()){
         System.out.println(litr.next());
      }
      
      //Setting element at the end of list
      litr.set("June");
      
      System.out.println("Navigating the list in backward direction:");
      while(litr.hasPrevious()){
         System.out.println(litr.previous());
      }
    
  }

}
Output:
Navigating the list in forward direction:
Jan
Feb
March
April
May
Navigating the list in backward direction:
June
April
March
Feb
Jan

Conclusion

This tutorial provides detailed information on how to use Java List (List Interface in Java) methods with illustrations.

Reference:

https://en.wikipedia.org/wiki/Java_collections_framework#List_interface

Translate ยป