I'm trying to create a collision intentionally.
fun main(args: Array<String>) {
val india = Country("India1", 1000)
val india2 = Country("India2", 1000)
val countryCapitalMap: HashMap<Country, String> = hashMapOf()
countryCapitalMap.put(india, "Delhi1")
countryCapitalMap.put(india2, "Delhi2")
}
class Country(var name: String, var population: Long) {
override fun hashCode(): Int {
return if (name.length % 2 == 0) 31 else 95
}
override fun equals(obj: Any?): Boolean {
val other = obj as Country?
return if (name.equals(other!!.name, ignoreCase = true)) true else false
}
}
So, I have india and india2 objects. I've overridden equals() and hashCode() methods for Country so that:
india.hashCode() == india2.hashCode()--> trueindia.equals(india2)--> false
According to Collision resolution in Java HashMap and part of the article "Lets put this Country objects in hashmap", if key1 has result of hash(key.hashCode()) equal to the same operation on the key2 then there should be collision.
So, I put breakpoint to see content of countryCapitalMap and see that its size is 2. I.e. it contains two different entries and there is no linkedList. Hence, there is no collision.
My questions are:
Why countryCapitalMap has a size of 2? Why is there no collision?
Why doesn't HashMap creates a LinkedList with two entries with keys that is not equal but have the same hashCode?