List Interface in Java


➲ A list is the subinterface of a collection which is available in java.util package. Subinterface means an interface which extends other interface is called subinterface. Here list interface extends the collection interface.

➲ It is an ordered collection where elements are maintained by index positions because it uses an index based structure. In the list interface, the order is retained in which we add elements and we will get the same sequence while retrieving elements.

➲ It is used to store a collection of elements where duplicate elements are allowed. 
➲ List interface has three concrete subclasses. They are ArrayList, LinkedList, Vector, and Stack. These three subclasses implement the list interface.
ArrayList in Java | Example Program 

Properties of List Interface in Java


1. The list allows storing duplicate elements in Java. JVM differentiate duplicate elements by using 'index'. Index refers to the position of a certain object in an array. It always starts at zero. For example, Assume that there is a list with size 10. Suppose the first element is 'a' at zero index position and the second element is also 'a' which is at 9th position. Thus, there are two 'a' elements in the list at position 0 and 9 respectively.

So JVM will differentiate between both elements in the list based on their numeral position of the index. Therefore, the index is very useful and play an important role to differentiate objects.
2. It maintains insertion order. i.e. List can preserve the insertion order by using the index.
3. It allows for storing many null keys.
4. The list uses a Resizable array for their implementation. Resizable means we can increase or decrease the size of the array.
5. Except for LinkedList, ArrayList, and Vector is indexed based structure.
LinkedList in Java | LinkedList Method Example 6. It provides a special Iterator called a ListIterator that allow accessing the elements in the forward direction using hasNext() and next() methods. In reverse direction, it access elements using hasPrevious() and previous() methods. We can add, remove elements of the collection and can also replace the existing elements with the new element using ListIterator.

Methods of List Interface in Java


The list also contains some specific methods. They are as follows.

1. boolean add(Object o):

It starts to add the specified element from zero location. If the element is already present at zero location, it will add the next element at one position. 
List interface in Java with examples
For example, consider 1 in the above figure. 
     list.add("a"); // Here, list is object reference variable. 
     list.add("b");
➲ Return type is boolean and Input type is object.

2. void add(int index, Object o):

This method adds/insert the specified element at the particular position in the list. 
For example, suppose we want to add element "d" at 3rd position, we will call add(int index, Object o ) method.

    list.add(3,"d"); // It will add element "d" at 3rd position as shown in figure.

3. boolean addAll(Collection c):

Here, Collection c represents a group of elements. This method is used to add/insert a group of elements at the end of the last element.
For example, suppose we want to add three elements x, y, and z at position 0, 1, and 2 respectively.
     list.add("x");
     list.add("y");
     list.add("z");
Now we will create another group of elements  like this:
     list1.add("a");
     list1.add("b");
     list1.add("c");
     list.addAll(list1);  // It will add group of elements at the end of the last element. The last element is z. So, after z, it will add the list1 as shown in above figure.

4. boolean addAll(int index, Collection c):

It is used to add/insert a group of elements at a particular position in the list and shift the subsequent elements to the right by increasing their indices.
For example, suppose we want to add three elements at position 1, 2, and 3 respectively using list1 reference variable.
   list1.add("A");
   list1.add("B");
   list1.add("C");
Now we will create another group of elements using the list2 reference variable.
   list2.add("G");
   list2.add("H");
Assume that we want to add this group of elements at position 2 of the list1 then we will call addAll(int index, Collection c) method like this:

   list1.addAll(2, list2); // You will see that element C is shifted to the right at position 4 as shown in figure.

5. object remove(int index):

It is used to remove the element at a specified position in the list. For example, consider the above figure.
   list1.remove(2); // It will remove the element at 2nd position and element D which is at 3rd position, will be shifted to the left at the 2nd position. The output will be A, B, D.

6. object get(int index):

This method is used to return element/object stored at a specified position in the list. Return type of get() method is Object and input type is int[index of List].
For example:
   list1.get(2); // Output will be 'C'.

7. int indexOf(Object o):

It is used to return the index of a particular element of the first occurrence in the list. If the element is not present in the list then it will return -1. It takes as an argument as an element and returns as an integer value of that element as it is index value.

For example, suppose an element 'A' is present at position 0 and the same element is also present at position 9 in the list.
      list.indexOf("A"); // It will return integer value of an element "A" of first occurrence. i.e from zero position, not from position 9. So the output is 0.

8. int lastIndexOf(Object o):

It returns the index of the last occurrence of a specified element in the list. If the list does not contain that particular element, it will return -1.
For example: 
    list.lastIndexOf("A"); // Output will be 9.

9. object set(int index, Object o):

This method replaces the existing element at the specified position in the list with new specified element.
For example:
   list1.set(2,"Z");

10. ListIterator listIterator():

It returns listIterator of the elements in the list in proper sequence. 

11. ListIterator listIterator(int):

It returns a listIterator of the elements in the list in proper sequence, starting at the specified position in the list. 

How to create List Objects in Java?


Since List is an interface, So the object of the list can be created by following ways:
1. List p=new ArrayList();
2. List q=new LinkedList();
3. List r=new Vector();
4. List s=new Stack();

Generic List Object in Java


After the introduction of Generic in Java 1.5, we can restrict the type of object that can be stored in the list. It can be defined as follows:
1. List<data type> list=new ArrayList<data type>(); // This is the syntax for creating an object with a generic type parameter. 
For example:
   a. List<String> list=new ArrayList<String>();
   b. List<Integer> list=new ArrayList<Integer>();
   c. List<String> list1=new LinkedList<String>();
   d. List<obj> list=new ArrayList<obj>(); // obj is the type of object.
For example:
    List<Book> list=new ArrayList<Book>(); // Book is the type of object.

2. Starting from Java 1.7, we can use a diamond operator.
    a. List<String> str=new ArrayList<>();
    b. List<Integer> list=new LinkedList<>();

Java List Example Programs


Let's take example programs to understand all the above concepts.
Program  source  code  1: 
Let's create an example program where we will add both integer and string elements together. In this program, we will not use generic.
    package listPrograms; import java.util.ArrayList; import java.util.List; public class AddEx { public static void main(String[] args) { // Create a List. List al=new ArrayList(); //Here is no use of generic. No type safety. So, we can add both integer and string elements. // Adding elements using add() method with reference variable al. al.add(10); al.add(20); al.add(30); al.add(40); al.add("Shubh"); // Adding element to 4th position. al.add(4, 35); // Adding element to 5th position. al.add(5, 45); // Now print. System.out.println("Elements after adding :-"+al); } }
    Output: Elements after adding :-[10, 20, 30, 40, 35, 45, Shubh]
Program source code 2:
    package listPrograms; import java.util.ArrayList; import java.util.List; public class AddAllEx { public static void main(String[] args){ // Create a list1 with only String type. This means that Compiler will give errors if we try to put any elements other than String. List<String> al=new ArrayList<String>(); al.add("Apple"); al.add("Mango"); al.add("Orange"); al.add("Grapes"); System.out.println("List1 contain :-"+al); //Create another List2 with String type. List<String> al2=new ArrayList<String>(); al2.add("11"); al2.add("12"); al2.add("13"); System.out.println("List2 contain :-"+al2); //Adding List2 in List1 at 2nd position(i.e index=2) using addAll() method. al.addAll(2, al2); System.out.println("List1 after adding List2 at 2nd position :-"+al); } }
    Output: List1 contain :-[Apple, Mango, Orange, Grapes] List2 contain :-[11, 12, 13] List1 after adding List2 at 2nd position :-[Apple, Mango, 11, 12, 13, Orange, Grapes]
Program source code 3:
    package listPrograms; import java.util.ArrayList; import java.util.List; public class IndexOfEx { public static void main(String[] args){ List al=new ArrayList(); al.add("AA"); al.add("BB"); al.add("CC"); al.add("DD"); al.add("EE"); al.add("FF"); //To find the Index of any particular element, use obj.indexOf(object o) method. System.out.println("Index of CC: "+al.indexOf("CC")); System.out.println("Index of FF: "+al.indexOf("FF")); } }
    Output: Index of CC: 2 Index of FF: 5
Program  source  code  4:
    package listPrograms; import java.util.ArrayList; import java.util.List; public class GetMethodEx { public static void main(String[] args) { List al=new ArrayList(); //Adding Element using reference variable al. al.add("pen"); al.add("pencil"); al.add("ink"); al.add("notebook"); al.add("book"); al.add("paper"); // Now call get(int index) method to get elements from specified index and print them. System.out.println("First Element: " +al.get(0)); System.out.println("Fourth Element: " +al.get(3)); } }
    Output: First Element: pen Fourth Element: notebook

When you go for List?


1. List can be used when we want to allow or store duplicate elements.
2. It can be used when we want to store null elements.
3. When we want to preserve my insertion order, we should go for list.

Final words
Hope that this tutorial has covered almost all important points related to Java List interface with examples and related programs. I hope that you will have understood basic of Java list interface and enjoyed this tutorial.
Thanks for reading!

⏪ Prev Next ⏩