patternjavaModerate
Wrapper class for adding elements to HashSet
Viewed 0 times
elementshashsetaddingwrapperforclass
Problem
I have many object of class
In order to ensure that the potential future changes in
Is my approach OK, or are there more suitable ways to achieve my goal?
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?
Solution
Why build your own implementation when you can use the features available in the Java standard libraries?
IdentityHashMap gives you all the features you need, and a Java Stream/collector will allow you to extract the map easily from your collection....
Now, if the size of the
IdentityHashMap gives you all the features you need, and a Java Stream/collector will allow you to extract the map easily from your collection....
Collection tests = .....
Map uniques = tests.stream().collect(Collectors.toMap(
t -> t,
t -> t,
(t,u) -> t,
IdentityHashMap::new))Now, if the size of the
uniques is the same as the tests, you're good. The uniques Map is an IdentityHashMap where the key values are all identical instances (using ==). It supports a null key/value so that should be fine too.Code Snippets
Collection<Test> tests = .....
Map<Test,Test> uniques = tests.stream().collect(Collectors.toMap(
t -> t,
t -> t,
(t,u) -> t,
IdentityHashMap::new))Context
StackExchange Code Review Q#109095, answer score: 10
Revisions (0)
No revisions yet.