Computer >> Computer tutorials >  >> Programming >> Java

Difference between List and Set in Java


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

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

Sr. No.KeyListSet
1
Positional access 
The list provides positional access of the elements in the collection.
Set doesn't provide positional access to the elements in the collection
2
Implementation 
Implementation of List are ArrayList,LinkedList,Vector ,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 Set 
4
Ordering 
List maintains insertion order of elements in the collection 
Set doesn’t maintain any order 
5
Null Element 
The list can store multiple null elements 
Set can store only one null element

Example of List

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]

Example of Set

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, 4, 3, 5]