Sobes.tech
Junior — Middle

Kas saaksite selgitada hash-tabeli tööpõhimõtet ja kuidas andmed seal salvestatakse?

sobes.tech AI

Vastus AI-lt

Hash table is a data structure that provides very fast access to data via a key. Its working principle is based on the use of a hash function, which transforms the key into an array index where the corresponding value is stored.

When you need to store 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 recalculates the index, and the needed value is quickly found.

If two different keys produce the same index (collision), the common method used is chaining: the cell contains a list of all elements with that index, and the search is performed in 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.