Skip to content

Instantly share code, notes, and snippets.

@xanderblinov
Last active February 10, 2018 11:04
Show Gist options
  • Save xanderblinov/fcba6f09f751f3f25f01b70a7320e04f to your computer and use it in GitHub Desktop.
Save xanderblinov/fcba6f09f751f3f25f01b70a7320e04f to your computer and use it in GitHub Desktop.
HashSet and modifiable objects example
package com.test.hashset
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class HashSetUnitTest {
class Some(var a: Int, var b: Int) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Some) return false
if (a == other.a && b == other.b) return true
return false
}
override fun hashCode(): Int {
var result = 17
result = result * 31 + a
result = result * 31 + b
return result
}
override fun toString(): String {
return "Some(a=$a, b=$b)"
}
}
@Test
fun objectModificationCausesBrokenContains() {
val hashSet = HashSet<Some>()
val control = Some(1, 2)
hashSet.add(control)
control.a = 42
val contains = hashSet.contains(Some(42, 2))
assertFalse(contains)
}
@Test
fun objectWithouModificationAndCorrectContains() {
val hashSet = HashSet<Some>()
val control = Some(1, 2)
hashSet.add(control)
val contains = hashSet.contains(Some(1, 2))
assertTrue(contains)
}
@Test
fun objectWithModificationAndSetResizeAndIncorrectContains() {
val hashSet = HashSet<Some>()
val control = Some(1, 2)
hashSet.add(control)
control.a = 42
for (i in 3..100000) {
hashSet.add(Some(1, i))
}
val contains = hashSet.contains(control)
assertFalse(contains)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment