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

Queen's Attack II HackerRank Solution in Java with Explanation

Queen's Attack II Problem's Solution in Java (Chessboard Problem)   Problem Description : You will be given a square chess board with one queen and a number of obstacles placed on it. Determine how many squares the queen can attack.  A queen is standing on an n * n chessboard. The chess board's rows are numbered from 1 to n, going from bottom to top. Its columns are numbered from 1 to n, going from left to right. Each square is referenced by a tuple, (r, c), describing the row r and column c, where the square is located. The queen is standing at position (r_q, c_q). In a single move, queen can attack any square in any of the eight directions The queen can move: Horizontally (left, right) Vertically (up, down) Diagonally (four directions: up-left, up-right, down-left, down-right) The queen can move any number of squares in any of these directions, but it cannot move through obstacles. Input Format : n : The size of the chessboard ( n x n ). k : The number of obstacles...

Java Hashset HackerRank Solution | Programming Blog

Java Hashset HackerRank Solution with Explanation   Problem Statement :- In computer science, a set is an abstract data type that can store certain values, without any particular order, and no repeated values. {1,2,3} is an example of a set, but {1,2,2} is not a set. Today you will learn how to use sets in java by solving this problem. You are given n pairs of strings. Two pairs (a,b) and (c,d) are identical if a = c and b = d. That also implies (a,b) is not same as (b,a). After taking each pair as input, you need to print number of unique pairs you currently have. See full problem description in HackerRank Website :- https://www.hackerrank.com/challenges/java-hashset/problem Let's see solution of problem. import java.util.HashSet; import java.util.Scanner; public class Solution {     public static void main(String[] args) {         Scanner s = new Scanner(System.in);         System.out.println("Enter tot...