F
F
foonfyrick2021-02-03 09:23:10
Java
foonfyrick, 2021-02-03 09:23:10

HashMap collision?

So I create a HashMap, by default it has 16 cells, I insert several values ​​\u200b\u200binto it with a different key, the hash function checks, depending on the key, in which cell to insert the value.
Here I inserted the values:
map.put(1,"one");map.put(4,"four");map.put(2,"two");map.put(3,"three"),
places for their insertion into the hash table, the hash function determined, and they were inserted in turn in ascending key value.
But there is a situation when values ​​can have different keys but one hash code (I can’t generate such a situation), so, suppose I insert another element, and then it calculates the same hash code as the element ( 1,"one"), in this case, the article suggests 2 solutions:
1. Cell method - when each cell is a list of elements, which stores elements with the same hash code.
2. Addressing method - when an empty cell is searched for a value with the same hash code, somewhere after this value.

The problem is that they wrote about it, but they didn’t show how to implement it. And I can't understand whether it all automatically works when a new value is added to the hash table, or you need to create some methods yourself and describe the behavior in case of a collision.
And also, how to mark a cell as deleted so that the search algorithm is not violated?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2021-02-03
@foonfyrick

If we are talking about the standard HashMap, then, of course, everything works out of the box. There, conditionally, the method of chains is implemented. But, in fact, not chains are built there, but balanced trees (rb-tree).
If we are talking about a self-written implementation, then, of course, everything must be written in it by hand. In each cell - a list, or somehow look for an empty cell.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question