Difference Between List and Set in Java



In Java, List and Set are both interfaces that belong to the Collection framework. Both interfaces extend the Collection interface. They are both used to store a collection of objects as a single unit.

Before JDK 1.2, we used to use Arrays, Vectors, and Hashtable for grouping objects as a single unit.

Difference Table

The following are the key differences between List and Set ?

Sr. No. Key List Set
1 Positional Access The list provides positional access to the elements in the collection. The set doesn't provide positional access to the elements in the collection.
2 Implementation Implementations of List are ArrayList, LinkedList, Vector and Stack. Implementation of a set interface is HashSet and LinkedHashSet.
3 Duplicate We can store the duplicate elements in the list. We can't store duplicate elements in a Set.
4 Ordering A list maintains the insertion order of elements in the collection. A set doesn't maintain any order.
5 Null Element The list can store multiple null elements. A set can store only one null element.

List

Syntax

The following is the syntax of List ?

List<String> al = new ArrayList<String>();

Example

Below is an example of a List in Java ?

import java.util.List;
import java.util.ArrayList;
import java.util.LinkedList;
public class ListExample {
   public static void main(String[] args) {
      List<String> al = new ArrayList<String>();
      al.add("BMW");
      al.add("Audi");
      al.add("BMW");
      System.out.println("List Elements: ");
      System.out.print(al);
   }
}

Output

List Elements: 
[BMW, Audi, BMW]

Time Complexity: O(n), for adding and printing n elements.
Space Complexity: O(n), stores n elements in an `ArrayList`.

Set

Syntax

The following is the syntax of Set ?

Set<Integer> hset = new HashSet<Integer>();

Example

Below is an example of a Set in Java ?

import java.util.Set;
import java.util.HashSet;
import java.util.TreeSet;
public class SetExample {
   public static void main(String args[]) {
      int count[] = {2, 4, 3, 5};
      Set<Integer> hset = new HashSet<Integer>();
      try{
         for(int i = 0; i<4; i++){
            hset.add(count[i]);
         }
         System.out.println(hset);
      }
      catch(Exception e){
         e.printStackTrace();
      }
   }
}

Output

[2, 3, 4, 5]

Time Complexity: O(n), each `HashSet` insertion takes O(1), so overall O(n).
Space Complexity: O(n), stores n unique elements in `HashSet`.

Alshifa Hasnain
Alshifa Hasnain

Converting Code to Clarity

Updated on: 2025-03-27T19:34:11+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements