{{theTime}}

Search This Blog

Total Pageviews

HashSet equals() Definition with example

What is the output of the following code:

import java.util.HashSet;
import java.util.Set;
public class HashSetEquals
{   
    public static void main(String str[]) throws Exception {
        Set nameSet = new HashSet<>() ;
        nameSet.add("USA") ;
        nameSet.add("Canada") ;
        Set cntrySet = new HashSet<>() ;
        cntrySet.add("USA") ;
        cntrySet.add("Canada") ;
        System.out.println(cntrySet.equals(nameSet)) ;
    }
}

Answer:   true.

import java.util.HashSet;
import java.util.Set;
public class HashSetEquals
{   
    public static void main(String str[]) throws Exception {
        Set nameSet = new HashSet<>() ;
        nameSet.add("USA") ;
        nameSet.add("Canada") ;
        nameSet.add("Brazil") ;
        Set cntrySet = new HashSet<>() ;
        cntrySet.add("USA") ;
        cntrySet.add("Canada") ;
        System.out.println(cntrySet.equals(nameSet)) ;
    }
}

Answer:   false.

import java.util.HashSet;
import java.util.Set;
public class HashSetEquals
{   
    public static void main(String str[]) throws Exception {
        Set nameSet = new HashSet<>() ;
        nameSet.add("USA") ;
        nameSet.add("Canada") ;
        nameSet.add("Canada") ;
        Set cntrySet = new HashSet<>() ;
        cntrySet.add("USA") ;
        cntrySet.add("Canada") ;
        System.out.println(cntrySet.equals(nameSet)) ;
    }
}

Answer:   true

The equals method for HashSet compares the specified object with this set for equality. Returns true if the specified object is also a set, the two sets have the same size, and every member of the specified set is contained in this set (or equivalently, every member of this set is contained in the specified set).

No comments:

Top LLMs in 2025

Navigating the AI Landscape: Key Differences Between Top LLMs in 2025 As of late September 2025, the large language model (LLM) arena is m...