Akshat-coder2106 opened a new pull request, #1554:
URL: https://github.com/apache/commons-lang/pull/1554
Summary
Replace the commutative XOR-based hashCode() implementation in Pair and
Triple with Objects.hash() to improve hash distribution and eliminate
collisions for permuted elements.
The Problem
The current implementation uses a simple XOR of the element hash codes:
return Objects.hashCode(getKey()) ^ Objects.hashCode(getValue());
This leads to two significant issues:
Commutativity: Pair.of("A", "B") and Pair.of("B", "A") result in identical
hash codes, causing 100% collisions for permutations.
Self-Cancellation: For identical elements like Pair.of("A", "A"), the hash
code becomes 0 because X⊕X=0.
The Fix
Updated both Pair.java and Triple.java to use Objects.hash(...), which
employs a prime multiplier (31) to ensure that the order of elements
significantly impacts the resulting hash.
Modified Files:
src/main/java/org/apache/commons/lang3/tuple/Pair.java
src/main/java/org/apache/commons/lang3/tuple/Triple.java
Technical Verification
The fix was verified by adding assertions to existing test methods in
ImmutablePairTest and ImmutableTripleTest to maintain a clean test suite.
Local Results:
Permutation Check: Pair.of("A", "B").hashCode()
= Pair.of("B", "A").hashCode().
Identity Check: Pair.of("A", "A").hashCode()
=0.
Build Status: mvn clean test -Dtest=ImmutablePairTest,ImmutableTripleTest
passed with 41 successful tests.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]