I have two sets in Java that compare Item
objects. Is there a method to compare the sets so that Item
\'s equals
method is invoked and
This is the default behaviour, if it's not what you're seeing then check that you're overriding hashCode as well. See the following code for an example:
public static void main(String[] args) {
Set- items1 = new HashSet
- ();
items1.add(new Item("item 1"));
items1.add(new Item("item 2"));
Set
- items2 = new HashSet
- ();
items2.add(new Item("item 1"));
items2.add(new Item("item 2"));
System.out.println(items1.equals(items2));
}
private static class Item {
private String id;
public Item(String id) {
this.id = id;
}
@Override
public int hashCode() {
return id.hashCode();
}
@Override
public boolean equals(Object obj) {
return id.equals(((Item)obj).id);
}
}
This outputs:
true