Difference between list and set in java

Difference between list and set in java

Difference between List and Set in java can be based on below given parameters.
1. Duplicate Object
  • List allows duplicate elements to be stored in it.
  • Set doesn’t allow duplicate element. All the element needs to be unique.
2. Order Maintenance
  • List generally maintains the insertion order.
  • In set maintenance of insertion order depends on the implementing class. (HashSet-> order not guaranteed, LinkedHashSet-> Order is maintained)
3. Null value
  • In List, one can store unlimited null values
  • In Set, only one null value is permitted.
4. Implementations
  • ArrayList class, LinkedList class and Vector class implements List interface.
  • HashSet class, LinkedHashSet class and TreeSet class implements Set interface.
5. Traversal
  • We can use both ListIterator and Iterator to traverse elements in List.
  • We cannot use ListIterator to iterate Set. In order to traverse Set use Iterator.
Example of list and set implementation in java code
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class ListandSet {

      public static void main(String[] args) {

            //Implentation of list
            List<String> arrayList = new ArrayList<String>();
            System.out.println("List elements:"+ arrayList);

            //Implementation of set
            Set<String> set = new HashSet<String>();
            System.out.println("Set elements:"+ set);




List elements:[A, B, A, C, D]
Set elements:[A, B, C, D]

Notice, the duplicate element "A" is not stored in set while it is stored in List.
We have covered major difference between list vs set.

Java Interview Questions

Would you like to see your article here on tutorialsinhand. Join Write4Us program by

About the Author
Rohanjit Kumar
Technology geek, loves to write and share knowledge with the world. Having 9+ years of IT experience. B.Tech in Computer Science & Engineering
Page Views :    Published Date : Jul 12,2020  
Please Share this page

Related Articles

Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!