An Introduction to List in Java

If you want an ordered collection, that can even handle duplicate elements, then list in Java is the perfect way to go. By ordered collection, it means that the elements remain in the same order in which they were inserted. Since it’s ordered, it allows the scope of performing index-based operations on it such as insert, delete, update, search, etc. 

The list is an interface in Java, which is a child interface of Collection. You can access it using java.util package. The classes that implement the List interface in Java are LinkedList, ArrayList, Vector, Stack, etc. However, the most frequently used one is the ArrayList. The List interface in Java is a factory of another interface called the ListIterator interface, and this allows everyone to move backward and forward through the list. 

Some of the useful features of a List in Java to be noted are - 

  • It allows duplicate elements
  • It can also accommodate null elements inside it
  • It is index-based, meaning you can insert and access elements using a 0-based index
  • Classes such as ArrayList, LinkedList, Stack, Vector, etc. implement this interface
  • Some list methods will throw some exceptions if it’s not possible to modify the collection. This includes exceptions such as UnsupportedOperationException, ClassCastException, etc.

This guide will explore the various aspects of List in Java and help you get hands-on experience through some practical examples.

Declaration of List Interface in Java

As discussed, the List is an interface in Java that extends the collection interface. The list interface can be declared using the following syntax - 

public interface List<E> extends Collection<E>

List Methods in Java

Some useful methods for List in Java are as follows: 

Methods

Usage

int size()

It is used to return the total number of elements in the List.

void add(int index, Object obj)

It is used to insert the element or object at the specified index.

boolean add(Object obj)

This method is used to append the element at the end of the list.

boolean addAll(int index, Collection c)

This method is used to add all the elements of the collection c to the list on which this method is invoked. starting from the index mentioned in the parameter. It preserves all the elements in the list as elements. It only gets shifted and is not overwritten. And it returns true if there is any change, else it returns false.

boolean isEmpty()

It is used to check whether or not the list is empty.

Object get(int index)

This get method when invoked on a list returns the object/element at the index specified in the parameter.

int indexOf(Object obj)

This method returns the position/index of the first occurrence of the object specified in the parameter. If such an object is not present in the list, it returns -1.

int lastIndexOf(Object obj)

This method will return the index of the last occurrence of the object specified in the parameter or returns -1 if no such object is found.

boolean contains(Object obj)

This method will return true if the list contains the object specified in the parameter, else it will return false.

Object set(int index, Object obj)

This method will replace the object at the specified index in the list with the object specified in the parameter.

Object remove(int index)

This method removes the object at the specified index in the list, compacts the list, and returns the object deleted.

void clear()

This method removes all the elements or objects from the list.

boolean remove(Object obj)

This method removes the first occurrence of the object specified and returns true if the operation is successful, else false.

boolean retainAll(Collection<?> c)

This method retains only those elements in the list that are present in the specified collection.

ListIterator listIterator()

It returns an iterator that points towards the start of the list.

ListIterator listIterator(int index)

It returns an iterator that points towards the index specified in the parameter. 

List subList(int start, int end)

This method returns a portion of the list from the start index (inclusive) to the end index (exclusive).

Object[] toArray()

This method returns an array that contains all the elements of the list in the same order.

default void replaceAll(UnaryOperator<E> operator)

This method replaces all the elements/objects in the list by the result that’s returned after applying the operator on the element.

default void sort(Comparator<super E> c)

This method sorts the list based on the comparator that’s passed in the parameter.

List in Java Vs. ArrayList

The Collection framework in Java provides a set of interfaces and classes that makes everyone’s life much easier. There are interfaces such as Queue, Set, DeQue, List, and there are classes such as LinkedList, ArrayList, HashSet, Vector, PriorityQueue, LinkedHashSet, TreeSet.

You might have noticed the difference here. The List in Java is an interface, and the ArrayList is a class that implements the List interface. 

Full Stack Java Developer Course

The Gateway to Master Web DevelopmentExplore Course
Full Stack Java Developer Course

List in Java

As discussed earlier, the list is an interface that is the child interface of the collection framework. It can store duplicate elements, null values, can traverse through them in both directions, and perform index-based operations on them. You can access it through Java.util package. 

Consider an example that explains the List in Java.

import java.util.*; 
public class Hello {
      public static void main(String[] args) 
      { 
          //Implement ArrayList class using the myList.
          List<String> myList = new ArrayList<String>();
         
          //Add String objects to the list
          myList.add("Welcome ");
          myList.add("to "); 
          myList.add("Simplilearn"); 
          System.out.println(myList); 
      } 
  }  

Output - 

ListinJava

In the above example, you have implemented the ArrayList class from the List interface and added a few string objects to it. It can also implement other classes such as LinkedList, vector, Stack, etc. from the List interface. 

ArrayList in Java

Unlike arrays in Java, ArrayList is a dynamic array that has no size limit. It’s ordered, which means we can perform index-based operations and store duplicates in it. It’s much more flexible and helpful than the traditional array in Java.

The ArrayList class in Java implements the List interface and inherits the AbstractList class. Please note that you can’t use primitive data types such as char, int, etc. with it. Instead, you can use wrapper classes for each of them. 

Consider the example below to understand it better.

  import java.util.*; 
  public class Hello {
          public static void main(String[] args) 
          { 
              ArrayList<Integer> l = new ArrayList<Integer>(); 
              l.add(1);
              l.add(2); 
              l.add(3); 
              System.out.println(l); 
          } 
      }  

Output - 

ArrayListinJava

Key Differences

List

ArrayList

It’s categorized as an interface.

It’s a class that implements the list interface.

The list interface extends the collection framework.

It extends the AbstractList class.

It allows faster object manipulation compared to ArrayList.

It’s slower than a list.

You can’t instantiate them.

It can be instantiated.

They are not dynamic.

We can expand them dynamically.

Common Operations for a List in Java

Creating a List in Java

You need to import the java.util package to use the List in Java. Let’s see how to create lists in Java.

List <type> myArrayList= new ArrayList();   
List <type> myLinkedList = new LinkedList();   
List <type> myVector = new Vector();   
List <type> myStack = new Stack();

The following example creates a simple Integer ArrayList and prints the empty list.

import java.util.*; 
public class Hello {
        public static void main(String[] args) 
        { 
            List<Integer> intList = new ArrayList<Integer>();
            System.out.println(intL); 
        } 
    }  

Output - 

IntegerArrayList

Adding Elements to a List

To add elements to the list, the add() method comes to play. There are two different versions of this method. They are - 

  • void add(Object obj): This method simply adds an object at the end of the list.
  • void add(int index, Object obj): This method adds the object at the specified index.

Let’s see how to do so.

import java.util.*; 
public class Hello {
  public static void main(String[] args) 
      { 
          List<Integer> intList = new ArrayList<Integer>();
          intList.add(1);
          intList.add(3);
          intList.add(1, 2);
          System.out.println(intList); 
      } 
  }  

Output - 

Addingelements

Changing Elements in a List

The set() method for Lists in Java is used to change or modify objects and elements in the lists. Consider the example below.

import java.util.*; 
public class Hello {
  public static void main(String[] args) 
      { 
          List<Integer> intList = new ArrayList<Integer>();
          intList.add(1);
          intList.add(3);
          intList.add(1, 2);
          intList.set(1, 58);
          System.out.println(intList); 
      } 
  }  

In the above example, it has changed the element at index 1, to 58.

Output -

Changingelements

Removing Elements in a List

There are two methods, in fact, they are variants of the same ‘remove method’ that is used to remove elements in a list. These are - 

  • remove(Object obj): This method removes the first occurrence of the specified object in the list.
  • remove(int index): This method removes the object at the specified index in the list.

Let’s see how to do the same.

import java.util.*; 
public class Hello {
  public static void main(String[] args) 
      { 
          List<String> list = new ArrayList<String>();
          list.add("Welcome");
          list.add("to");
          list.add("Simplilearn");
          list.add("to");
          list.add("learn");
         
          //The list is ["Welcome", "to", "Simplilearn", "to", "learn"]

          list.remove("to");

          //The list is ["Welcome", "Simplilearn", "to", "learn"]

          list.remove(0);

          //The list is ["Simplilearn", "to", "learn"]

          System.out.println(list); 
      } 
  }  

Output - 

Removingelements

FREE Java Certification Training

Learn A-Z of Java like never beforeEnroll Now
FREE Java Certification Training

Iterating the List in Java

Although there are several ways to iterate a list in Java, the easiest one of all is to use a simple for loop in combination, with the get method in Java. You can also use the advanced for-each loop to iterate the list. Keep scrolling to see how to do so.

import java.util.*; 
public class Hello {
  public static void main(String[] args) 
      { 
          List<String> list = new ArrayList<String>();
          list.add("Welcome");
          list.add("to");
          list.add("Simplilearn");
          list.add("to");
          list.add("learn");
         
          //Basic for loop
          for(int i=0; i<list.size(); i++){
              System.out.print(list.get(i) + " ");
          }
          System.out.println();
          //For-each loop
          for(String s:list){
              System.out.print(s + " ");
          }

      } 
  }  

Output - 

Iteratingthelist

Convert an Array into List in Java

Method 1.

If you use the Arrays class for viewing the arrays as a list, you can’t make any modifications because it will throw up an UnsupportedOperationException. Instead, iterate over the array using a for loop and create a list. Let’s see how to do that.

import java.util.*; 
public class Hello {
  public static void main(String[] args) 
      { 
          String[] message = {"Welcome", "to", "Simplilearn"};
          List<String> messageList = Arrays.asList(message);
          System.out.println(messageList);

          //We can't do modifications such as remove, clear, etc. in this list.

          //Let's use for loop to copy the array elements to a new list.

          List<String> myMessage = new ArrayList<>();
          for(String s:messageList){
              myMessage.add(s);
          }
          System.out.println(myMessage);
          myMessage.clear();
      } 
  }  

Output - 

Method1

Method 2.

You can also use the Collections.addAll() to copy all the elements of an array to a list.

import java.util.*; 
public class Hello {
  public static void main(String[] args) 
      { 
          String[] message = {"Welcome", "to", "Simplilearn"};

          List<String> myMessage = new ArrayList<>();
         
          Collections.addAll(myMessage, message);

          System.out.println(myMessage);

          myMessage.add("It's");
          myMessage.add("Awwsome");

          System.out.println(myMessage);

          myMessage.clear();
      } 
  }  

Output - 

Method2

Convert a List into an Array in Java

In the first method, YOU can go the traditional way by using a ‘for loop’ to create a new array by traversing through the list.

But there’s a simple way to do this. It can be done by simply using the toArray() method on the list to convert the list into an array in Java. Here is how to do so.

import java.util.*; 
public class Hello {
  public static void main(String[] args) 
      { 

          List<String> myMessage = new ArrayList<>();
         
          myMessage.add("Welcome");
          myMessage.add("to");
          myMessage.add("Simplilearn");

          System.out.println(myMessage);

          String[] messageArray = new String[myMessage.size()];
          messageArray = myMessage.toArray(messageArray);
         
          //toString method converts an array object to string
          System.out.println(Arrays.toString(messageArray));
     
      } 
  }  

Output - 

ListintoArray

Get a firm foundation in Java, the most commonly used programming language in software development with the Java Certification Training Course.

Conclusion

To conclude, this guide discussed the popular - List in Java. It started with a basic introduction of how lists can be useful and explored their implementation as well. It then moved on to discuss the several methods that can be used with lists that make code implementation easier. Then, it discussed the differences between a list and an ArrayList in Java with the help of simple examples.

It skimmed through a few examples where you implemented some common operations with lists and ArrayLists. Finally, it explored different methods using which one can convert lists into arrays and vice-versa in Java. 

Hopefully, this guide has helped you get started with the list part of the giant collection programming in Java. Have any questions for us? Leave them in the comments section, and our experts will answer them for you right away!

Cheers. Happy Learning!

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.