Site icon TestingDocs.com

What is the difference between Set and List

Table of Contents

Toggle

Introduction

In this tutorial, we will discuss the differences between Set and List. Set and List are both interfaces in the Java Collection Framework. Both extend the core Collection interface.

https://www.testingdocs.com/java-collection-framework/

Set

The Set is an unordered collection. The order of the elements in the collection is not guaranteed. The Set doesn’t allow duplicate elements in the collection.

package list;

import java.util.HashSet;
import java.util.Set;

public class SetDemo {

    Set<String> set = new HashSet<String>();
    public SetDemo() {
        set.add("One");
        set.add("One");
        set.add(null);  // null is allowed

        set.add("Two");
        set.add("Three");
        set.add("Four");
    }

    //traverse method using for each
    public void traverse() {
        for(String str : set) {
            System.out.println(str); // order is not guaranteed
             }
    }

    public int setSize() {
        return set.size();
    }

    public static void main(String[] args) {
        SetDemo d = new SetDemo();
        d.traverse();
        System.out.println("Set Size=" + d.setSize());//duplicates are removed
        }
}

 

Output:

null
One
Four
Two
Three
Set Size=5

List

A List is an ordered collection and it maintains the insert order of the elements. The list allows duplicates into the collection.

package list;

import java.util.ArrayList;
import java.util.Iterator; 
import java.util.List; 

public class ListDemo { 
    List<String> list = new ArrayList<String>(); 
    public ListDemo() { 
        list.add("One");
        list.add("Two"); 
        list.add("Three"); 
        list.add("Four");
        list.add("Five"); 
        list.add("One"); // allows duplicates,see output 
        } 
        
        //traverse method using for each 
       public void traverse() { 
        for(String str : list) {
            System.out.println(str); // maintains the order
            }
    } 
    
    public static void main(String[] args) {
        ListDemo d = new ListDemo();
        d.traverse(); 
    } 
}

 

Output:

One
Two
Three
Four
Five
One

Exit mobile version