API: Fix equals and hashCode in CharSequenceSet#9245
Conversation
| set2.add(new StringBuffer("v2")); | ||
| set2.add("v3"); | ||
|
|
||
| Set<CharSequence> set3 = Collections.unmodifiableSet(set2); |
There was a problem hiding this comment.
I am primarily interested in wrapping CharSequenceSet into UnmodifiableSet in CharSequenceMap.
f914a5f to
b9b9561
Compare
| @Override | ||
| public boolean equals(Object o) { | ||
| if (this == o) { | ||
| public boolean equals(Object other) { |
There was a problem hiding this comment.
See Set#equals() and AbstractSet#equals() for background.
| return wrapperSet.equals(that.wrapperSet); | ||
| try { | ||
| return containsAll(that); | ||
| } catch (ClassCastException | NullPointerException unused) { |
There was a problem hiding this comment.
While this class does not throw these exceptions now, it may in the future. These exceptions are valid outcomes defined by the Set API. Therefore, I am respecting that to be safe.
| @Override | ||
| public int hashCode() { | ||
| return Objects.hashCode(wrapperSet); | ||
| return wrapperSet.stream().mapToInt(CharSequenceWrapper::hashCode).sum(); |
There was a problem hiding this comment.
The Set API requires the hash code to be a sum of hash codes of all elements. See Set#hashCode().
|
|
||
| Set<CharSequence> set3 = Collections.unmodifiableSet(set2); | ||
|
|
||
| Set<CharSequenceWrapper> set4 = |
There was a problem hiding this comment.
This one works too now.
szehon-ho
left a comment
There was a problem hiding this comment.
Looks good. Another option is to extend java AbstractSet, wondering if we considered it?
|
@szehon-ho, I started by extending |
|
Thanks, @szehon-ho! |

The
equalsandhashCodebehaviors inCharSequenceSetcontradict theSetAPI, which prohibits wrapping these sets into unmodifiable wrappers inCharSequenceMap#keySet.