diff --git a/src/commonMain/kotlin/com/github/quillraven/fleks/collection/bitArray.kt b/src/commonMain/kotlin/com/github/quillraven/fleks/collection/bitArray.kt index b757881..000d6c5 100644 --- a/src/commonMain/kotlin/com/github/quillraven/fleks/collection/bitArray.kt +++ b/src/commonMain/kotlin/com/github/quillraven/fleks/collection/bitArray.kt @@ -154,16 +154,12 @@ class BitArray( } override fun hashCode(): Int { - if (bits.isEmpty()) { - return 0 + var result = 1 + for (i in bits.size - 1 downTo 0) { + val word = bits[i] + result = 31 * result + (word xor (word ushr 32)).toInt() } - - val word = length() ushr 6 - var hash = 0 - for (i in 0..word) { - hash = 127 * hash + (bits[i] xor (bits[i] ushr 32)).toInt() - } - return hash + return result } override fun equals(other: Any?): Boolean { diff --git a/src/commonTest/kotlin/com/github/quillraven/fleks/collection/BitArrayTest.kt b/src/commonTest/kotlin/com/github/quillraven/fleks/collection/BitArrayTest.kt index 3f92590..1eb8bfb 100644 --- a/src/commonTest/kotlin/com/github/quillraven/fleks/collection/BitArrayTest.kt +++ b/src/commonTest/kotlin/com/github/quillraven/fleks/collection/BitArrayTest.kt @@ -189,4 +189,33 @@ internal class BitArrayTest { assertEquals(expected3, bits3.toString()) assertEquals(expected4, bits4.toString()) } + + @Test + fun testHashCode() { + // empty BitArray + val bits = BitArray() + bits.hashCode() + + // test for single long + bits.set(0) + bits.hashCode() + bits.set(1) + bits.hashCode() + bits.set(63) + bits.hashCode() + + // BitArray resizes to two longs in the LongArray + bits.set(64) + bits.hashCode() + bits.set(65) + bits.hashCode() + bits.set(127) + bits.hashCode() + + // BitArray resizes to more than two longs + bits.set(128) + bits.hashCode() + bits.set(129) + bits.hashCode() + } }