0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Unity-配列?リスト?辞書?系統

Posted at

Unity C# における配列に似たデータ構造とその使い分け

Unity C# には、配列 (Array) に似たデータ構造がいくつか存在します。それぞれに異なる特徴があり、用途に応じて適切なものを選ぶことが重要です。本記事では、各データ構造の特徴と使い分けを解説します。

1. 配列 (T[])

特徴

  • 固定長(サイズ変更不可)
  • 高速なインデックスアクセス (array[i])
  • 宣言時に要素数が必要
  • メモリ効率が良い

使いどころ

  • 要素数が決まっている場合
  • 高速なインデックスアクセスが必要な場合

int[] numbers = new int[3] {1, 2, 3};
Debug.Log(numbers[0]);

2. リスト (List<T>)

特徴

  • 可変長(要素の追加・削除が可能)
  • Add(), Remove() で要素の管理が簡単
  • using System.Collections.Generic; が必要

使いどころ

  • 配列のように使いたいが、サイズが不定な場合
  • 頻繁に要素の追加・削除を行う場合

using System.Collections.Generic;
List<int> numbers = new List<int> {1, 2, 3};
numbers.Add(4);
numbers.Remove(2);
Debug.Log(numbers[0]);

3. 辞書 (Dictionary<TKey, TValue>)

特徴

  • キーと値のペアで管理
  • インデックスアクセス不可、キーでアクセス
  • 高速な検索 (ContainsKey())

使いどころ

  • 名前やIDをキーにしてデータを管理したい場合
  • 高速な検索を必要とする場合

using System.Collections.Generic;
Dictionary<string, int> scores = new Dictionary<string, int>();
scores["Alice"] = 90;
Debug.Log(scores["Alice"]);

4. キュー (Queue<T>)

特徴

  • 先入れ先出し(FIFO: First In, First Out)
  • Enqueue() で追加、Dequeue() で取り出し

使いどころ

  • 処理待ちのデータ管理
  • イベント処理やタスク管理

using System.Collections.Generic;
Queue<string> queue = new Queue<string>();
queue.Enqueue("A");
queue.Enqueue("B");
Debug.Log(queue.Dequeue()); // "A"

5. スタック (Stack<T>)

特徴

  • 後入れ先出し(LIFO: Last In, First Out)
  • Push() で追加、Pop() で取り出し

使いどころ

  • 履歴管理(例: 戻るボタン)
  • 再帰的な処理

using System.Collections.Generic;
Stack<string> stack = new Stack<string>();
stack.Push("A");
stack.Push("B");
Debug.Log(stack.Pop()); // "B"

6. HashSet<T>(重複なしのリスト)

特徴

  • 重複を許さない
  • 高速な検索 (Contains()) が可能
  • インデックスアクセス不可

使いどころ

  • 重複を避けたいデータ管理
  • ユニークなデータの集合

using System.Collections.Generic;
HashSet<int> numbers = new HashSet<int> {1, 2, 3};
numbers.Add(2); // 追加されない
Debug.Log(numbers.Contains(2));

データ構造の比較表

データ構造 特徴 使いどころ
T[](配列) 固定長、高速アクセス 小さなデータ、変更不要な配列
List<T> 可変長、追加・削除が簡単 一般的なリスト管理
Dictionary<K,V> キーで値を管理、高速検索 IDや名前で管理するデータ
Queue<T> FIFO、順番に処理 待機列やタスク管理
Stack<T> LIFO、最後に追加したものを先に取り出す 戻るボタンや履歴管理
HashSet<T> 重複なし、高速検索 一意性を保ちたいデータ

まとめ

Unity C# には、配列に似たデータ構造がいくつもあり、それぞれ異なる用途に適しています。

  • 配列 (T[]) は固定長で高速アクセスが必要な場合に適用
  • List<T> は可変長のリストで、最も一般的に使用される
  • Dictionary<TKey, TValue> はキーと値のペアでデータを管理する際に便利
  • Queue<T> はFIFOで順番に処理が必要な場合
  • Stack<T> はLIFOで履歴管理に適用
  • HashSet<T> は重複を許さないデータ管理に最適

用途に応じて適切なデータ構造を選び、効率的なコードを書くようにしましょう!

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?