Home > OS >  How to Distinguish Object in Java Set
How to Distinguish Object in Java Set

Time:09-21

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 ?

CodePudding user response:

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.

CodePudding user response:

You need to override the equals method.

See here for details: https://www.geeksforgeeks.org/overriding-equals-method-in-java/

in your Custom class you would write a method called equals and use the @Override annotation:

@Override
public boolean equals(Object o) {

    // If the object is compared with itself then return true 
    if (o != null && o.a == this.a && o.b == this.b) {
        return true;
    }else{
        return false;...

This will cause a collision when you add two objects with matching a and b values, thus preventing it from being added to the set again.

  • Related