A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/java/set-equals-method-in-java-with-examples/ below:

Set equals() Method in Java

Set equals() Method in Java

Last Updated : 11 Jul, 2025

In Java, the equals() method of the Set class is used to compare two sets for equality. It checks if two sets contain the same elements regardless of their order.

Example 1: This example demonstrates how to compare two HashSet collections for equality of type string using the equals() method.

Java
// Java program to demonstrate 
// the working of equals() method
import java.util.*;

public class Geeks {
    public static void main(String[] argv)
    {
        // Creating object of Set
        Set<String> s1 = new HashSet<String>();

        s1.add("A");
        s1.add("B");
        s1.add("C");
        s1.add("D");
        s1.add("E");

        System.out.println("First Set: " + s1);

        // Creating another object of Set
        Set<String> s2 = new HashSet<String>();

        s2.add("A");
        s2.add("B");
        s2.add("C");
        s2.add("D");
        s2.add("E");

        System.out.println("Second Set: " + s2);

        // comparing first Set to another
        // using equals() method
        boolean value = s1.equals(s2);

        System.out.println("Are both set equal? " + value);
    }
}

Output
First Set: [A, B, C, D, E]
Second Set: [A, B, C, D, E]
Are both set equal? true
Syntax of equals() Method

boolean equals(Object o)

Example 2: This example demonstrates how to compare two HashSet collections for equality of type integer using the equals() method.

Java
// Java Program to demonstrates 
// the working of equals() method
import java.util.*;

public class Geeks {
    public static void main(String[] argv)
    {
        // Creating object of Set
        Set<Integer> s1 = new HashSet<Integer>();

        s1.add(10);
        s1.add(20);
        s1.add(30);
        s1.add(40);
        s1.add(50);

        System.out.println("First Set: " + s1);

        // Creating another object of Set
        Set<Integer> s2 = new HashSet<Integer>();

        s2.add(10);
        s2.add(20);
        s2.add(30);

        System.out.println("Second Set: " + s2);

        // comparing first Set to another
        // using equals() method
        boolean value = s1.equals(s2);

        System.out.println("Are both set equal? " + value);
    }
}

Output
First Set: [50, 20, 40, 10, 30]
Second Set: [20, 10, 30]
Are both set equal? false


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4