Can you explain the principle of operation of a hash table and how data is stored in it?
sobes.tech AI
Answer from AI
A hash table is a data structure that provides very fast access to data by key. It works based on a hash function that converts the key into an index in an array where the corresponding value is stored.
When storing a key-value pair, the hash function calculates the index, and the data is placed in the array cell at that index. When searching by key, the hash function again calculates the index, and the value is quickly retrieved.
If two different keys produce the same index (collision), a common method is chaining — storing a list of all elements with that index in the cell, and searching through this list.
Example in Dart (Flutter):
void main() {
Map<String, int> hashTable = {};
hashTable['apple'] = 5;
hashTable['banana'] = 3;
print(hashTable['apple']); // 5
}
Here, Map is an implementation of a hash table, where the key is a string and the value is a number.