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 ?