How to define my own element class for use with Set

I have the following code:

public class MyElement { String name; String type; MyElement(String name, String type) { this.name = name; this.type = type; } } public class Test { public static void main(String[] args) { Set<MyElement> set = new HashSet<MyElement>(); set.add(new MyElement("foo", "bar")); set.add(new MyElement("foo", "bar")); set.add(new MyElement("foo", "bar")); System.out.println(set.size()); System.out.println(set.contains(new MyElement("foo", "bar"))); } } 

which, when executed, returns with:

 3 false 

I expected the result to be 1 and true. Why are my elements not recognized the same and how can I fix this? Thanks, Wayne.

+4
source share
2 answers

You need to implement equals(Object o) and hashCode() in MyElement for a common contract. It is missing that Set.contains() will use a default implementation that compares the memory address of objects. Since you create a new instance of MyElement in the contains call, it returns as false.

+11
source

You must override the equals (MyElement me) function. Equals returns a boolean

Otherwise, you verify that the two elements are the same instance of the object, and not that their internal content is the same.

 MyElement(String name, String type) { this.name = name; this.type = type; } public boolean Equals<MyElement>(MyElement me) { return this.name.equals(me.name) && this.type.equals(me.type); } 
0
source

Source: https://habr.com/ru/post/1343380/


All Articles