LoginSignup
0
0

Kotlin HashMap

Posted at

HashMapの使い方

HashMapは、Kotlinで提供されている一種のコレクションで、キーと値のペアを格納するためのデータ構造です。各キーは一意であり、それぞれのキーは特定の値にマッピングされます。HashMapは、キーに基づいて迅速に値を検索することができます。 以下に、HashMapの基本的な使用方法を示します:

fun main() {
    // HashMapの作成
    val map = HashMap<Int, String>()

// 要素の追加
    map[1] = "one"
    map[2] = "two"

// 要素の取得
    val one = map[1]  // "one"

// 要素の削除
    map.remove(1)

// HashMapのサイズ取得
    val size = map.size  // 1

// HashMapの全要素をループで処理
    for ((key, value) in map) {
        println("Key: $key, Value: $value")
    }
}

このように、HashMapはキーと値のペアを効率的に管理するための強力なツールです。

公式の情報

Hash table based implementation of the MutableMap interface

MutableMapインターフェースのハッシュテーブル・ベースの実装


IntelliJ IDEAで実行してプログラムを実行しています。

Returns an empty new HashMap.

空の新しい HashMap を返します。

fun main(args: Array<String>) {
    val map = hashMapOf<Int, Any?>()
    println("map.isEmpty() is ${map.isEmpty()}") // true

    map[1] = "x"
    map[2] = 1.05
    // Now map contains something:
    println(map) // {1=x, 2=1.05}
}

Returns a new HashMap with the specified contents, given as a list of pairs where the first component is the key and the second is the value.

指定された内容を持つ新しいHashMapを返します。指定された内容は、最初のコンポーネントをキー、2番目のコンポーネントを値とするペアのリストとして与えられます。

fun main(args: Array<String>) {
    val map: HashMap<Int, String> = hashMapOf(1 to "x", 2 to "y", -1 to "zz")
    println(map) // {-1=zz, 1=x, 2=y}
}

以上が、HashMapの使い方でした。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0