List Interface In Java

List Interface In Java: This list interface is an extended collection interface that gives optimal solutions with concepts like positional access, iteration, etc. This post will discuss various operations on a list interface in Java.

The topics that are going to be discussed in this post are:

  • List interface in Java
  • Creating List Objects
  • Different Method of List Interface
  • Different Operation On List Interface

List Interface In Java

When we must represent a group of individual objects as a single entity where duplicates are allowed and insertion order is preserved, we should go for the List interface. The List interface has preserved the order, so whatever the operation is inserted, accessed, iterated, and removed according to the order in which they appear internally in the Java List.

Each element in the List has an index, so we can access the elements with the help of indexes, which also helps us search for an element on a List interface.

In the Java Collection framework, some classes are implemented in the List interface. These classes are ArrayList, LinkedList, Vectors, and Stack classes.

List Interface In Java Explanation
List Interface In Java Explanation

Following is the syntax to implement the list interface in Java.

public interface List<E> extends Collection<E>

Creating List Objects

From the above discussion, we get to know that a list is an interface, and we can create the instance of a List interface in the following ways:

List obj1 = new ArrayList();
List obj2 = new LinkedList();
List obj3 = new Vector();
List obj4 = new Stack();

//After the release of generics, we can restrict the type of the object as well.
List <object> list = new ArrayList<object>();

List Interface Methods

MethodDescription
void add(int index, E element)It is used to insert elements at a particular position
boolean add(E e)It appends the elements at the end of the list
boolean addAll(int index, Collection<? extends E> c)It appends elements in a specified collection at the end of the list
void clear()Removes all the elements from the list
boolean equals(Object o)It compares the specified object with elements in the list
int hashcode()It returns the hash code value of the list
E get(int index)It fetches elements from a particular location of the list
boolean isEmpty()It checks if the list is empty or not
int lastIndexOf(Object o)Returns the index value of the specified object
Object[] toArray()It returns an array with all the elements in a list in a correct order
T[] toArray(T[] a)Returns an array with all the elements in a list
boolean contains(Object o)It returns true if the specified element is present in the list
boolean containsAll(Collection<?>c)It checks for multiple elements in a list
int indexOf(Object o)Returns the index of the element in the first occurrence
E remove(int index)Removes the elements at the specified location
boolean remove(Object o)It removes the first occurrence of the specified element
boolean removeAll(Collection<?> c)Removes all elements from the list
void replaceAll(UnaryOperator operator)Replace all elements with specified values
void retainAll(Collection<?> c)Retains all elements at a specified location
E set(int index, E element)Replace the specified element at the specified location
void sort(Comparator<? Super E> c)Sorts the list based on specified comparator
Spliterator spliterator()Creates spliterator over elements
List<E> subList (int fromIndex, int toIndex)Fetches elements in a given range
int size()Returns the number of elements in a list

As you can see from the above table, the List interface provides many methods. Using those methods, we can do different operations like positional access, searching operation, iteration, etc.

So, Let’s take some examples and try to understand how the List interface works:

Positional Access:

In the below example, we will learn how to access an element of the List interface by using the index of that element.

package com.SoftwareTestingO.Java.basics;
import java.util.ArrayList;
import java.util.List;
public class Demo 
{
   public static void main(String[] args)
   {
      List<Integer> list = new ArrayList<Integer>();
      list.add(0,1);
      list.add(1,3);
      list.add(2,5);
      list.add(3,7);
      System.out.println("The Complete List:- "+ list);
      list.remove(3);
      System.out.println("Third Index Element is: "+list.get(2));
      list.set(2,7);
      System.out.println("After Update the 2nd element Value: "+list);
   }
}

Output:

The Complete List:- [1, 3, 5, 7]
Third Index Element is: 5
After Update the 2nd element Value: [1, 3, 7]

Search Operation Using List Interface:

The list interface provides some methods for searching for an element and returns the numeric position of those elements. Those methods are :

int indexOf(Object o)
int lastIndexOf(Object o)

If there are so many elements in the list, then to traverse or iterate those elements, we can use the Listiterator. A list iterator is a bidirectional iterator, which means we can traverse in both forward and backward directions. We have discussed iterators in Java in detail in a separate post.

Range-view In List Interface:

The list also provides methods to get some of the portions of elements between two indices. The list interface operator provides the List subList(int fromIndex, int toIndex) method. You can use this method below:

// Java program to demonstrate the subList operation
// on List interface.
package com.SoftwareTestingO.Java.basics;
import java.util.ArrayList;
import java.util.List;
public class Demo
{
   public static void main (String[] args)
   {
      // Type safe array list, stores only string
      List<String> l = new ArrayList<String>(5);

      l.add("SoftwareTestingo");
      l.add("Practice");
      l.add("TestingQuiz");
      l.add("IDE");
      l.add("Courses");

      List<String> range = new ArrayList<String>();

      // Return List between 2nd(including)
      // and 4th element(excluding)
      range = l.subList(2, 4);
      System.out.println(range);
   }
}

Important Points Of List Interface

  • Java List is a member of the Java Collections Framework.
  • The list allows you to add duplicate elements.
  • The list allows you to have ‘null’ elements.
  • In the list, many default methods in Java 8, for example, replaceAll, sort, and spliterator.
  • List indexes start from 0, just like arrays.
  • The list supports Generics, and we should use it whenever possible. Using Generics with List will avoid ClassCastException at runtime.

Write a program to add elements to a list in Java.

package com.java.Softwaretestingblog;
import java.util.ArrayList;
import java.util.List;
public class AddingElementsInList {
   public static void main(String[] args) {
      // TODO Auto-generated method stub
      List<String> li=new ArrayList<String>();
      li.add("Software");
      li.add("Testing");
      li.add("Blog");
      System.out.println(li); // tostring is bydefault override in collection
   }
}

Output:

[Software , Testing , Blog]

Remove Element Java Program: Write a Program to Remove Element From List In Java With Example?

package com.java.Softwaretestingblog;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class MyItrRemoveElement {
   public static void main(String[] args) {
      // TODO Auto-generated method stub
      String removeElem = "Perl";
      List<> myList = new ArrayList();
      myList.add("Java");
      myList.add("Unix");
      myList.add("Oracle");
      myList.add("C++");
      myList.add("Perl");
      System.out.println("Before remove:");
      System.out.println(myList);
      Iterator<> itr = myList.iterator();
      while(itr.hasNext())
      {
         if(removeElem.equals(itr.next())){
            itr.remove();
         }
      }
      System.out.println("After remove:");
      System.out.println(myList);
   }
}

Output:

Before remove: [Java, Unix, Oracle, C++, Perl]
After remove: [Java, Unix, Oracle, C++]

I love open-source technologies and am very passionate about software development. I like to share my knowledge with others, especially on technology that's why I have given all the examples as simple as possible to understand for beginners. All the code posted on my blog is developed, compiled, and tested in my development environment. If you find any mistakes or bugs, Please drop an email to softwaretestingo.com@gmail.com, or You can join me on Linkedin.

Leave a Comment