Key differences between List and Set in Java

List in Java

List is an interface found in the java.util package and is part of Java’s Collection Framework. It represents an ordered collection (also known as a sequence) where elements are indexed numerically. This interface allows for duplicate elements and provides control over where in the list each element is inserted. Users can access elements by their integer index (position in the list), search for elements, and iterate over the list. Lists typically allow multiple null elements if the specific List implementation supports it. Common implementations of the List interface include ArrayList, LinkedList, and Vector, each offering different performance trade-offs for various storage and operation scenarios, such as rapid access, efficient insertion or removals, and memory usage considerations.

Functions of List in Java:

  • Add Elements:

Lists allow you to add elements to the collection, either at a specified index or at the end of the list.

  • Remove Elements:

Elements can be removed from the list using their index or directly by specifying the object.

  • Get Elements:

You can access any element in a list by its index.

  • Set Elements:

Lists allow setting or replacing the element at a specified index with a new value.

  • Size and Clear:

Lists provide methods to get the size of the list and to remove all elements from the list, clearing it completely.

  • Sort:

Lists can be sorted either naturally (if elements are Comparable) or using a specified Comparator.

  • Iterator:

Lists provide iterators that allow you to traverse the elements in the list in a forward direction, and list iterators that additionally support bidirectional traversal and modification operations.

  • SubList:

Create a view of a portion of the list, which is a backed list such that any modification in the sublist will be reflected in the original list.

  • Contains:

Check if a list contains a specific element.

  • IndexOf / LastIndexOf:

Find the index of the first or last occurrence of an element in the list.

Example of List in Java:

Here’s an example of how you can use the List interface in Java with some of its common methods:

import java.util.ArrayList;

import java.util.List;

public class ListExample {

    public static void main(String[] args) {

        // Create a List instance with an ArrayList

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

        // Adding elements to the list





        // Printing all elements in the list

        System.out.println(“Initial List: ” + fruits);

        // Accessing elements by index

        System.out.println(“Element at index 2: ” + fruits.get(2));

        // Adding an element at a specific position

        fruits.add(2, “Blueberry”);

        System.out.println(“After inserting Blueberry at index 2: ” + fruits);

        // Removing an element

        fruits.remove(“Date”); // by object

        fruits.remove(2); // by index

        System.out.println(“After removing Date and element at index 2: ” + fruits);

        // Replacing an element

        fruits.set(1, “Blackberry”);

        System.out.println(“After setting Blackberry at index 1: ” + fruits);

        // Check if list contains an element

        if (fruits.contains(“Apple”)) {

            System.out.println(“Apple is in the list”);


        // Getting the size of the list

        System.out.println(“Size of list: ” + fruits.size());

        // Clearing the list


        System.out.println(“List after clearing: ” + fruits);



In this example:

  • List of type String is declared and instantiated using ArrayList.
  • Several add methods are used to insert elements, demonstrating how to insert at the end and at a specific index.
  • The get method is used to access an element at a specific position.
  • The remove method is used to remove elements by both index and object reference.
  • The set method replaces an element at a specified index.
  • The contains, size, and clear methods are demonstrated for checking list contents, size, and clearing the list, respectively.

Set in Java

Set is an interface in the java.util package, part of the Java Collections Framework. It represents a collection that contains no duplicate elements. Unlike the List interface, Set does not define the order in which elements are stored, making it suitable for when uniqueness is more important than ordered data. Implementations of the Set interface include classes like HashSet, LinkedHashSet, and TreeSet. HashSet is the most common implementation, which stores its elements in a hash table, offering fast access times. LinkedHashSet maintains a linked list of its elements, preserving the insertion order, while TreeSet stores elements in a sorted tree structure, maintaining natural order. Set implementations are particularly useful for operations like deduplication, membership tests, and mathematical set operations.

Functions of Set in Java:

  • Add elements:

Adds an element to the set. If the element already exists, it does not get added again, ensuring all elements are unique.

  • Remove elements:

Removes a specified element from the set, if it is present.

  • Contains:

Checks if a specified element is present in the set.

  • Size:

Returns the number of elements in the set.

  • IsEmpty:

Checks if the set is empty.

  • Clear:

Removes all elements from the set, resulting in an empty set.

  • Iterator:

Provides an iterator over the set elements, allowing traversal of the set.

  • toArray:

Converts the set into an array, containing all the elements in the set.

  • addAll(Collection<? extends E> c):

Adds all of the elements in the specified collection to this set if they’re not already present.

  • removeAll(Collection<?> c):

Removes from this set all of its elements that are contained in the specified collection.

  • retainAll(Collection<?> c):

Retains only the elements in this set that are contained in the specified collection.

  • equals(Object o):

Compares the specified object with this set for equality.

  • hashCode():

Returns the hash code value for this set.

  • stream():

Returns a sequential Stream with this set as its source.

  • forEach(Consumer<? super E> action):

Performs the given action for each element of the Set until all elements have been processed or the action throws an exception.

Example of Set in Java:

This example demonstrates creating a HashSet, adding elements to it, checking if an element is present, and iterating over the set.

import java.util.HashSet;

import java.util.Set;

public class SetExample {

    public static void main(String[] args) {

        // Create a HashSet

        Set<String> fruitSet = new HashSet<>();

        // Add elements to the HashSet






        // Attempt to add a duplicate element

        boolean isAdded = fruitSet.add(“Apple”);

        System.out.println(“Was ‘Apple’ added again? ” + isAdded); // This will print false

        // Check if the Set contains a specific element

        if (fruitSet.contains(“Mango”)) {

            System.out.println(“Mango is in the set.”);


        // Print the size of the Set

        System.out.println(“The set contains ” + fruitSet.size() + ” elements.”);

        // Iterate over the Set using an enhanced for loop

        System.out.println(“Contents of the set:”);

        for (String fruit : fruitSet) {



        // Remove an element from the Set


        // Check the size after removal

        System.out.println(“The set contains ” + fruitSet.size() + ” elements after removal.”);

        // Clear all elements


        System.out.println(“The set is empty: ” + fruitSet.isEmpty());




  • HashSet Creation:

HashSet instance is created to hold strings.

  • Adding Elements:

Strings representing names of fruits are added to the set. Duplicate elements are automatically rejected.

  • Checking Elements:

The program checks if “Mango” is present in the set.

  • Iterating:

The set is iterated using an enhanced for loop to print all its elements.

  • Removing and Clearing:

Demonstrates removing an element (“Orange”) and clearing the entire set.

Key differences between List and Set in Java

Aspect List Set
Ordered Collection Yes, insertion order is retained No specific order (unless using LinkedHashSet)
Allows Duplicates Yes No
Data Access Indexed access (get/set) Access via iteration only
Implementation Classes ArrayList, LinkedList, etc. HashSet, TreeSet, LinkedHashSet
Null Values Multiple nulls allowed Typically one null (depends on implementation)
Method of Uniqueness No uniqueness enforced Uniqueness enforced
Best Use Managing ordered data Unique element collection
Performance (adding items) Generally constant time Depends on hash function (HashSet)
Performance (access time) Fast indexed access Slower, no indexed access
Interface Type List extends Collection Set extends Collection
Methodology More functionality, e.g., sort() Simpler, focused on uniqueness
Positional Access Supports positional access and manipulation Does not support positional access
Iteration Order Predictable iteration order Unpredictable in HashSet
Footprint May use more memory for indices Typically less memory without indices
Typical Methods add(int index, E element), get(int index) add(E element), contains(Object o)

Key Similarities between List and Set in Java

  • Collection Interface:

Both List and Set are part of the Java Collections Framework and extend the Collection interface. This inheritance implies that they both adhere to the fundamental contract of collections, including basic methods like add(), remove(), contains(), size(), and more.

  • Generics Support:

Both support generics, allowing them to be parameterized with a specific type of objects which helps in enforcing type safety.

  • Iterable:

Since both are collections, they are iterable using Java’s enhanced for-loop and iterators. This allows for iterating over elements sequentially in the case of a List, and over a unique set of elements in the case of a Set.

  • Containment Checks:

Both interfaces provide methods to check whether a particular element is present in the collection (contains(Object o)), making it easy to perform quick membership checks.

  • Modifiability:

Lists and Sets generally allow dynamic modifications such as adding, removing, and clearing of elements, except for their immutable implementations.

  • Use of Internal Data Structures:

Both use underlying data structures to store elements. Lists typically use arrays or linked node structures (like ArrayList and LinkedList), while Sets use structures like hash tables or trees (like HashSet or TreeSet).

  • Collection-based Constructors:

Both List and Set implementations often provide constructors that accept another Collection to initialize the new instance, facilitating the conversion between different types of collections.

  • Functional Programming Support:

With the advent of Java 8, both List and Set support stream operations which can be used to perform functional-style operations, such as mapping, filtering, and folding operations.

error: Content is protected !!