Scientech Easy Java List Interface with Examples | Scientech Easy

Saturday, October 20, 2018

Java List Interface with Examples

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 index based structure. In the list interface, the order is retained in which we add elements and the same sequence we will get 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.

Properties of List Interface


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 from 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. That is List can preserve the insertion order by using the index.
3. It allows 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.
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.

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, Java list add, List of Objects in Java.
List methods with array representation

For example: see the above picture. 
     list.add("a"); // 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"); // Look at the above picture.
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 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. Last element is z so after z, it will add the list1. See in picture. 
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 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 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 the addAll(int index, Collection c) method like this:
   list1.addAll(2, list2); // You will see that element C is shifted to the right at the position 4.

5. object remove(int index): It is used to remove the element at a specified position in the list. 
For example: See the picture.
   list1.remove(2); // It will remove the element at 2nd position and the 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 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 is 9.
9. object set(int index, object o): This method replace 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. 
Note:  We will learn the programs related to all methods and listIterator in further ArrayList tutorial.

Creating List Objects:

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:

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:
    List<String> list=new ArrayList<String>();
    List<Integer> list=new ArrayList<Integer>();
    List<String> list1=new LinkedList<String>();
    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.
    List<String> str=new ArrayList<>();
    List<Integer> list=new LinkedList<>();
    
Let's see some example programs to understand all the above concepts.
Program  source  code  1: 
    package com.scientecheasy; 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 com.scientecheasy; 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 com.collectiontest; 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); 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 com.collectiontest; import java.util.ArrayList; import java.util.List; public class GetMethodEx { public static void main(String[] args) { List al=new ArrayList(); //Adding Element using al reference variable. al.add("pen"); al.add("pencil"); al.add("ink"); al.add("notebook"); al.add("book"); al.add("paper"); // Now call the get(int index) method to get the element 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:
I hope that this article will help to understand the Java List interface with examples and related programs. We will discuss more best example programs after learning ArrayList class. So in the next tutorial, we will learn ArrayList in detail with a lot of interesting examples and programs.

Next ➨ ArrayList in Java


Popular