Sobes.tech
Junior — Middle

Millistes olukordades on soovitatav kasutada andmestruktuuri HashMap võtme-väärtuse paaride salvestamiseks?

sobes.tech AI

Vastus AI-lt

HashMap is recommended for use when you need to store data efficiently and access it quickly by key. Main situations:

  • Frequent search, insert, and delete operations by key with amortized complexity O(1).
  • When the order of elements is not important.
  • Keys are unique and well hashed.

For example, if you need to store application settings, where the key is the setting name and the value is its parameter, HashMap allows quick retrieval of the needed value.

Kotlin example:

val map = HashMap<String, Int>()
map["apple"] = 3
map["banana"] = 5
println(map["apple"]) // 3