• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

SoftwareTestingo - Jira Selenium Protractor Testing SDLC Agile Methodology

Java Selenium Tutorial & Testing Interview Questions

  • Home
  • Interview Questions
  • Java
  • Java Programs
  • Test Cases
  • Selenium
  • Manual Testing
  • Difference
  • Search
SoftwareTestingo » Java » Java Tutorial » List Interface In Java

List Interface In Java

Last Updated on: August 15, 2020 By Softwaretestingo Editorial Board

What We Are Learn On This Post

  • List Interface In Java
  • Creating List Objects
  • List Interface Methods
  • Important Points Of List Interface

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, we are going to discuss various operations on a list interface in Java.

The topics which are going to discuss on this post is:

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

List Interface In Java

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

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

In the Java Collection framework, we have some classes which are implemented the List interface that 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

As from the above discussion, we get to know that list is an interface and we can create the instance of List interface by 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

Method Description
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) Replaces all elements with specified values
void retainAll(Collection<?> c) Retains all elements at a specified location
E set(int index, E element) Replaces 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 List interface provides so many methods. By using those methods, we can do different operations like positional access, searching operation, iteration, etc.

So Let’s take some example and try to understand how the List interface is working:

Positional Access:

In the below example we are going to learn how we can access an element of List interface by using the index of that elements

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:

List interface provides some methods for search 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 for traverse or iterate those elements we can use the Listiterator. List iterator is a bidirectional iterator that means we can traverse in both forward and backward direction. We have discussed in detail in a separate post of Iterators in Java.

Range-view In List Interface:

List also providing some methods to get some of the portions of elements between two indices. For this operator list interface is providing List subList(int fromIndex, int toIndex) method, you can use this method like 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 list, got 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 Element In 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("Manoj");
      li.add("Kumar");
      li.add("Rana");
      System.out.println(li); // tostring is bydefault override in collection
   }
}

Execution: The output link

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);
   }
}

Execution: Chk For the execution result link

Output:

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

Ref: article

    Filed Under: Java Tutorial Tagged With: Java Collection

    Reader Interactions

    Leave a Reply Cancel reply

    Your email address will not be published. Required fields are marked *

    Primary Sidebar

    Join SoftwareTestingo Telegram Group

    Tutorials Important Links

    • Software Testing Jobs
    • Manual Testing Tutorial
    • Selenium Tutorial
    • Core Java Tutorial
    • TestNG Tutorial
    • Java Programs
    • Selenium Programs
    • Manual Test Cases
    • Interview Tips
    • Contact US
    • www.softwaretestingo.com

    Important Links

    • Software Testing Interview Questions
    • Agile Interview Questions
    • Manual Testing Interview Questions
    • Testing Interview Questions
    • Selenium Interview Questions
    • Selenium Real Time Interview Questions
    • Selenium WebDriver Interview Questions
    • Automation Framework Interview Questions
    • Appium Interview Questions
    • TestNG Interview Questions
    • Java Interview Questions
    • Core Java Interview Questions

    Categories

    Copyright © 2021 SoftwareTestingo.com ~ Contact Us ~ Sitemap ~ Privacy Policy