Skip to main content

What is List interface in Java | Guide to ArrayList, LinkedList and Vector Class

List interface in Java with ArrayList, LinkedList and Vector Class   

List interface in Java with ArrayList, LinkedList and Vector Class with Exmaples

List Interface (java.util.List) :

List is an ordered collection. It is also known as sequence.

List is child interface of Collection framework. List comes under java.util package.

We can access any element by their index and search for element also in the List. List maintains ordered elements and duplicate also.

Methods of List Interface :

  1. add()
  2. addAll()
  3. clear()
  4. contains()
  5. containsAll()
  6. equals()
  7. get()
  8. hashCode()
  9. indexOf()
  10. isEmpty()
  11. iterator()
  12. lastIndexOf()
  13. listIterator()
  14. remove()
  15. removeAll()
  16. retainAll()
  17. set()
  18. size()
  19. subList()
  20. toArray()

For use functionality of List interface we can use following classes :

  1. ArrayList
  2. LinkedList
  3. Vector
  4. Stack

ArrayList Class :

We can say, ArrayList is better version of Array. It is resizable array. means as simple array, we does not have to specify size of array.

The Java ArrayList class can store a group of many objects. We can not store primitives (int, double, float, etc) in ArrayList only Objects (Integer, Float, etc) are allowed.

ArrayList class is same as Vector class. the only difference is ArrayList is non-synchronized and Vector is synchronized.

How to create new ArrayList?

ArrayList list = new ArrayList();

OR

List list = new ArrayList();

It will create new empty arraylist.

Lets jump on code for some operations we can perform on ArrayList.

import java.util.ArrayList;

public class ArrayListDemo {

    public static void main(String[] args) {
       
        ArrayList<Integer> list = new ArrayList<Integer>();
        list.add(1);
        list.add(4);
        list.add(2);
        list.add(90);
        list.add(9);
        list.add(5);
       
        System.out.println("Get elements by specific index : "+ list.get(1));
       
        System.out.println("Get index of specific element : "+ list.indexOf(1));
       
        System.out.println("Check if list is empty : "+ list.isEmpty());
       
        System.out.println("Check if list contains specific vlaue : "+ list.contains(2));
       
        System.out.println("Check if list is empty : "+ list.isEmpty());
       
        System.out.println("Replace element at specific index : "+list.set(1, 10));
       
        System.out.println("Remove an element at specific index : "+ list.remove(0));

        System.out.println("Iterate through arraylist : ");
       
        list.iterator().forEachRemaining(System.out::println);   
       
    }
}

Output :

Get elements by specific index : 4
Get index of specific element : 0
Check if list is empty : false
Check if list contains specific vlaue : true
Check if list is empty : false
Replace element at specific index : 4
Remove an element at specific index : 1
Iterate through arraylist :
10
2
90
9
5

LinkedList Class :

An ArrayList is an index based data structure backed by an Array. On the other hand, a LinkedList stores its data as a list of elements and every element is linked to its previous and next element. 

LinkedList is also not synchronized.

In LinkedList every element is Node, which keeps a reference to the next and previous one.

LinkedList class also implemets Deque interface, so we can use Queue implementation also.

When to use LinkedList over ArrayList?

When insertion and deletion operations are used frequently, LinkedList is better choice. 

import java.util.LinkedList;

public class LinkedListDemo {

    public static void main(String[] args) {
        LinkedList<Integer> list = new LinkedList<>();
        list.add(10);
        list.add(20);
        list.add(20);
        list.add(90);
        list.add(50);
        list.add(30);

        System.out.println("Size of list : "+list.size());
        
        //Adding element at First
        list.addFirst(60);
        
        //Adding element at last
        list.addLast(100);
        
        System.out.println("Getting index of last element : "+list.indexOf(100));
        
        list.iterator().forEachRemaining(System.out::println);

        //Removing first element
        list.removeFirst();
       
        //Removing last element
        list.removeLast();
       
        System.out.println("List size : "+list.size());
        
    }
}

Output :

Size of list : 6
Getting index of last element : 7
60
10
20
20
90
50
30
100
List size : 6

Types of Linked List :

There is Three types of Linked List in java.

  1. Singly linked list (Uni-directional)
  2. Doubly linked list (Bi-directional)
  3. Circular linked list

Vector Class :

Using Vector class, we can create resizable array same as Arraylist class. but there is some differences exist.

Vector class is synchronized, means it is thread safe. If one Thread is accessing vector then another Thread have to wait until previous one complete the operation on Vector.

import java.util.Vector;

public class LinkedListDemo {

    public static void main(String[] args) {

        Vector<String> vector = new Vector<String>();
        vector.add("Java");
        vector.add("Python");
        vector.add("JavaScript");
        vector.add("Dot Net");
        vector.add("Php");
        
        System.out.println("Getting element by index : "+ vector.get(1));
        
        System.out.println("Set element on specific index : "+ vector.set(3, "CSharp"));

        System.out.println("Remove element by index : "+ vector.remove(4));
        
        System.out.println(vector);
    }
}

Output :

Getting element by index : Python
Set element on specific index : Dot Net
Remove element by index : Php
[Java, Python, JavaScript, CSharp]

Stack Class :

Stack class is not implementing List interface directly but it extends Vector class and can use functionality of List interface.

Stack follows LIFO (Last in First out) order. means element add top of stack and removed from top only.

import java.util.Stack;

public class LinkedListDemo {

    public static void main(String[] args) {

        Stack<String> stack = new Stack<String>();
        stack.push("Java");
        stack.push("Python");
        stack.push("JavaScript");
        stack.push("Dot Net");
        stack.push("Php");
       
        System.out.println("Getting top element of Stack without remove : "+ stack.peek());
       
        System.out.println("Pop element form Stack : "+ stack.pop());
       
        System.out.println("Checking stack is empty or not : "+ stack.empty());
       
        System.out.println(stack);
    }
}

Output :

Getting top element of Stack without remove : Php
Pop element form Stack : Php
Checking stack is empty or not : false
[Java, Python, JavaScript, Dot Net]

       

 Happy learning. Happy coding.

Comments

Popular posts from this blog

Plus Minus HackerRank Solution in Java | Programming Blog

Java Solution for HackerRank Plus Minus Problem Given an array of integers, calculate the ratios of its elements that are positive , negative , and zero . Print the decimal value of each fraction on a new line with 6 places after the decimal. Example 1 : array = [1, 1, 0, -1, -1] There are N = 5 elements, two positive, two negative and one zero. Their ratios are 2/5 = 0.400000, 2/5 = 0.400000 and 1/5 = 0.200000. Results are printed as:  0.400000 0.400000 0.200000 proportion of positive values proportion of negative values proportion of zeros Example 2 : array = [-4, 3, -9, 0, 4, 1]  There are 3 positive numbers, 2 negative numbers, and 1 zero in array. Following is answer : 3/6 = 0.500000 2/6 = 0.333333 1/6 = 0.166667 Lets see solution Solution 1 import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.function.*; import java.util.regex.*; import java.util.stream.*; import static java.util.st

Flipping the Matrix HackerRank Solution in Java with Explanation

Java Solution for Flipping the Matrix | Find Highest Sum of Upper-Left Quadrant of Matrix Problem Description : Sean invented a game involving a 2n * 2n matrix where each cell of the matrix contains an integer. He can reverse any of its rows or columns any number of times. The goal of the game is to maximize the sum of the elements in the n *n submatrix located in the upper-left quadrant of the matrix. Given the initial configurations for q matrices, help Sean reverse the rows and columns of each matrix in the best possible way so that the sum of the elements in the matrix's upper-left quadrant is maximal.  Input : matrix = [[1, 2], [3, 4]] Output : 4 Input : matrix = [[112, 42, 83, 119], [56, 125, 56, 49], [15, 78, 101, 43], [62, 98, 114, 108]] Output : 119 + 114 + 56 + 125 = 414 Full Problem Description : Flipping the Matrix Problem Description   Here we can find solution using following pattern, So simply we have to find Max of same number of box like (1,1,1,1). And last