「毎日Unity」の技術ブログ

開発で役立つ情報を発信する

【UnityC#】HashSetの使い方

HashSetの使い方を自分用にメモすることにしました。

[ HashSetとは ]

HashSetとは特定の要素を含むかどうかの判定はArrayやListと比べ圧倒的に早いコレクションです。しかし、重複要素を持つこととindexを使って要素指定ができないという特徴を持ちます。どうしてもindexを使って要素指定をしたい場合は、ToList()などを使って要素指定が可能なコレクションに変換する必要があります。

[ 使い方 ]

宣言

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ScriptTest : MonoBehaviour
{
    void Start()
    {
        HashSet<string> HashSetTest = new HashSet<string>();
    }
}

初期化

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ScriptTest : MonoBehaviour
{
    void Start()
    {
        HashSet<string> HashSetTest = new HashSet<string>()
        {
            "ABC", 
            "DEF", 
            "GHI", 
        };
    }
}

要素の追加

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ScriptTest : MonoBehaviour
{
    void Start()
    {
        HashSet<string> HashSetTest = new HashSet<string>();

        HashSetTest.Add("ABC");
    }
}

要素の消去

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ScriptTest : MonoBehaviour
{
    void Start()
    {
        HashSet<string> HashSetTest = new HashSet<string>()
        {
            "ABC", 
            "DEF", 
            "GHI", 
        };

        HashSetTest.Remove("ABC");
    }
}

全要素の消去

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ScriptTest : MonoBehaviour
{
    void Start()
    {
        HashSet<string> HashSetTest = new HashSet<string>()
        {
            "ABC", 
            "DEF", 
            "GHI", 
        };

        HashSetTest.Clear();
    }
}

素数を取得

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ScriptTest : MonoBehaviour
{
    void Start()
    {
        HashSet<string> HashSetTest = new HashSet<string>()
        {
            "ABC", 
            "DEF", 
            "GHI", 
        };

        Debug.Log(HashSetTest.Count); // 3
    }
}

特定の要素を含むか

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ScriptTest : MonoBehaviour
{
    void Start()
    {
        HashSet<string> HashSetTest = new HashSet<string>()
        {
            "ABC", 
            "DEF", 
            "GHI", 
        };

        Debug.Log(HashSetTest.Contains(”ABC”)); // true
    }
}

[ 関連記事 ]

edunity.hatenablog.com