Junior — Middle
How does collision handling occur in data structures or databases?
sobes.tech AI
Answer from AI
Collision handling of keys (collisions) in data structures and databases depends on the used structure and storage mechanism.
In hash tables (e.g., map in Go):
- A collision occurs when two different keys have the same hash.
- Methods to resolve collisions include:
- Chaining: each cell in the hash table stores a list of elements with the same hash.
- Open addressing: upon collision, the next free cell is searched according to a certain rule (linear, quadratic probing, etc.).
In Go, the built-in map implements collision resolution internally, usually using chaining.
In databases:
- When inserting a record with a key that already exists (e.g., primary key), a conflict occurs.
- Depending on settings and operation type:
- The operation may be rejected with an error.
- "Upsert" commands (insert or update) can be used to update the existing record.
Thus, collision handling is either an internal mechanism of the data structure (as in hash tables) or application/DB logic that determines how to react to duplicate keys.