As community has pointed out in the comments, a Set
is not meant to store duplicate values. But for reasons like "interview question" or "library code that you can't change", you can force it to store duplicates by overriding equals
to always return false
.
For primitives or other objects not under your control, you can create a wrapper class around your value object and make its equals()
always return false
:
public class UnequalWrapper {
private int value;
//...constructor, getter, setter
@Override
public boolean equals(Object o) {
return false;
}
@Override
public int hashCode() {
return Objects.hashCode(value);
}
}
and then use it:
public static void main(String[] args) {
UnequalWrapper a = new UnequalWrapper(1);
UnequalWrapper b = new UnequalWrapper(2);
UnequalWrapper c = new UnequalWrapper(1);
Set<UnequalWrapper> set = Set.of(a, b, c);
set.forEach(wrapper -> System.out.println(wrapper.getValue()));
}
Output:
1
2
1
But again, this is not recommended, do not try this at home!
Edit:
If you are using a wrapper, you can omit equals()
and hashcode()
. This is because the Object
class' methods will check for object reference, which will be different if you are creating a new wrapper instance each time.