Search code examples
javaannotationssetlombokhashcode

How to Distinguish Object in Java Set


Hey Guys I want to store objects in a Set . But even if an object contains same key-value it's stored as a separate entity in the set

import java.util.HashSet;
import java.util.Set;
class HelloWorld {
    
    public static void main(String[] args) {
        System.out.println("Hello, World!");
        Set<Custom> set = new HashSet();
        set.add(new Custom(1,"HEY"));
        set.add(new Custom(1,"HEY"));
        System.out.println(set.size());
        for (Custom s : set) {
            System.out.println(s);
        }
    }
}

class Custom {
    private int a;
    private String b;

    Custom(int a,String b) {
        this.a = a;
        this.b = b;
    }
    public String toString() {
        return "a : " + Integer.toString(a) + "b : " + b;
    }

}

Prints

Hello, World!
2
a : 1b : HEY
a : 1b : HEY 

Can anyone suggest ways to store this as a same object . Does adding annotation of @EqualsAndHashCode works ?


Solution

  • Yes, that annotation works. If you don't override equals() or hashCode() methods, objects are only equal when they refer to the same object instance. This Lombok annotation can generate the two methods automatically. You can also exclude fields using transient modifier or @EqualsAndHashCode.Exclude. Read this article for more information.