I have many object of class Test
. I want to be sure that among them, there are no two objects o1
and o2
where o1==o2
. In order to achieve that, I want to add them all to a HashSet
and check if hashSet.size() == numberOfInitialObjects
.
In order to ensure that the potential future changes in equals
method of the Test
class will not affect my implementation, I wrote a simple wrapper so that instead of adding Test
objects to the HashSet
, the wrapper objects will be used. The code as such:
private class HashSetWrapper {
private final Test component;
public HashSetWrapper(Test component) {
this.component = component;
}
@Override
public int hashCode() {
int hash = 7;
hash = 89 * hash + Objects.hashCode(this.component);
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final HashSetWrapper other = (HashSetWrapper) obj;
return this.component == other.component;
}
}
Is my approach OK, or are there more suitable ways to achieve my goal?
Test.equals()
might break equivalence? If so, you have other things to worry about then. \$\endgroup\$equals()
method in your class. Every class extendsObject
class, andObject
class hasequals()
method. When you overrideequals()
method in your class, you can compare two objects of the same class. \$\endgroup\$equals
you should always also overridehashCode
, especially so when the intent is clearly to add a class to aHashSet
, where each item'shashCode
would be involved in the keying. At least, that's how it works in .net and I'd assume Java works similarly. \$\endgroup\$