18
16

LinkedHashMap (追加順序を保持するDictionary)

Last updated at Posted at 2014-10-02

JavaのLinkedHashMapが欲しいこともあると思うのだけど、そのためだけにライブラリを参照するのも何だかなと思い、さっと書いてみました。

(追記)内部実装をList<T>にした方が、多くの場合で高速じゃないかなと思い直したので、List<T>版を先に書いておきます。Remove()をほとんど呼ばないのであればたぶんこっちの方が速いでしょう。

(さらに追記)ジェネリックな順序付き辞書クラス OrderedDictionary という記事を見つけました。

LinkedHashMap.cs
/*
The MIT License (MIT)

Copyright (c) 2014 matarillo

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

using System;
using System.Collections.Generic;
using System.Linq;

public class LinkedHashMap<TKey, TValue> : IDictionary<TKey, TValue>
{
    private readonly Dictionary<TKey, int> dict;

    private readonly List<KeyValuePair<TKey, TValue>> list;

    #region constructor

    public LinkedHashMap()
    {
        dict = new Dictionary<TKey, int>();
        list = new List<KeyValuePair<TKey, TValue>>();
    }

    public LinkedHashMap(IEqualityComparer<TKey> comparer)
    {
        dict = new Dictionary<TKey, int>(comparer);
        list = new List<KeyValuePair<TKey, TValue>>();
    }

    public LinkedHashMap(int capacity)
    {
        dict = new Dictionary<TKey, int>(capacity);
        list = new List<KeyValuePair<TKey, TValue>>(capacity);
    }

    public LinkedHashMap(int capacity, IEqualityComparer<TKey> comparer)
    {
        dict = new Dictionary<TKey, int>(capacity, comparer);
        list = new List<KeyValuePair<TKey, TValue>>(capacity);
    }

    public LinkedHashMap(IEnumerable<KeyValuePair<TKey, TValue>> source)
    {
        if (source == null)
        {
            throw new ArgumentNullException("source");
        }
        var countable = source as System.Collections.ICollection;
        if (countable != null)
        {
            dict = new Dictionary<TKey, int>(countable.Count);
            list = new List<KeyValuePair<TKey, TValue>>(countable.Count);
        }
        else
        {
            dict = new Dictionary<TKey, int>();
            list = new List<KeyValuePair<TKey, TValue>>();
        }
        foreach (var pair in source)
        {
            this[pair.Key] = pair.Value;
        }
    }

    public LinkedHashMap(IEnumerable<KeyValuePair<TKey, TValue>> source, IEqualityComparer<TKey> comparer)
    {
        if (source == null)
        {
            throw new ArgumentNullException("source");
        }
        var countable = source as System.Collections.ICollection;
        if (countable != null)
        {
            dict = new Dictionary<TKey, int>(countable.Count, comparer);
            list = new List<KeyValuePair<TKey, TValue>>(countable.Count);
        }
        else
        {
            dict = new Dictionary<TKey, int>(comparer);
            list = new List<KeyValuePair<TKey, TValue>>();
        }
        foreach (var pair in source)
        {
            this[pair.Key] = pair.Value;
        }
    }

    #endregion

    #region IDictionary implementation

    public bool ContainsKey(TKey key)
    {
        return dict.ContainsKey(key);
    }

    public void Add(TKey key, TValue value)
    {
        DoAdd(key, value);
    }

    private void DoAdd(TKey key, TValue value)
    {
        var pair = new KeyValuePair<TKey, TValue>(key, value);
        list.Add(pair);
        dict.Add(key, list.Count - 1);
    }

    public bool Remove(TKey key)
    {
        int index;
        if (!dict.TryGetValue(key, out index))
        {
            return false;
        }
        DoRemove(index, key);
        return true;
    }

    private void DoRemove(int index, TKey key)
    {
        list.RemoveAt(index);
        dict.Remove(key);
        for (var i = index; i < list.Count; i++)
        {
            var pair = list[i];
            dict[pair.Key] = i;
        }
    }

    public bool TryGetValue(TKey key, out TValue value)
    {
        int index;
        if (dict.TryGetValue(key, out index))
        {
            value = list[index].Value;
            return true;
        }
        value = default(TValue);
        return false;
    }

    private int IndexOf(TKey key, TValue value)
    {
        int index;
        if (dict.TryGetValue(key, out index))
        {
            if (EqualityComparer<TValue>.Default.Equals(value, list[index].Value))
            {
                return index;
            }
        }
        return -1;
    }

    public TValue this[TKey key]
    {
        get { return list[dict[key]].Value; }
        set
        {
            int index;
            if (!dict.TryGetValue(key, out index))
            {
                DoAdd(key, value);
                return;
            }
            DoSet(index, key, value);
        }
    }

    private void DoSet(int index, TKey key, TValue value)
    {
        var pair = new KeyValuePair<TKey, TValue>(key, value);
        list[index] = pair;
    }

    public ICollection<TKey> Keys
    {
        get
        {
            return list.Select(p => p.Key).ToArray();
        }
    }

    public ICollection<TValue> Values
    {
        get
        {
            return list.Select(p => p.Value).ToArray();
        }
    }

    #endregion

    #region ICollection implementation

    public void Clear()
    {
        dict.Clear();
        list.Clear();
    }

    public int Count
    {
        get { return dict.Count; }
    }

    public bool IsReadOnly
    {
        get { return false; }
    }

    #endregion

    #region IEnumerable implementation

    public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
    {
        return list.GetEnumerator();
    }

    #endregion

    #region IEnumerable implementation

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

    #endregion

    #region explicit ICollection implementation

    void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item)
    {
        Add(item.Key, item.Value);
    }

    bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item)
    {
        return (IndexOf(item.Key, item.Value) >= 0);
    }

    void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
    {
        list.CopyTo(array, arrayIndex);
    }

    bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item)
    {
        var index = IndexOf(item.Key, item.Value);
        if (index < 0)
        {
            return false;
        }
        DoRemove(index, item.Key);
        return true;
    }

    #endregion
}

以下は、追記する前のLinkedList<T>版。Javaの実装に近いのはたぶんこっちだと思う。Remove()を何度も呼ぶ可能性が高いならこっちの方が速くなるかもしれない。

LinkedHashMap.cs
/*
The MIT License (MIT)

Copyright (c) 2014 matarillo

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

using System;
using System.Collections.Generic;
using System.Linq;

public class LinkedHashMap<TKey, TValue> : IDictionary<TKey, TValue>
{
    private readonly Dictionary<TKey, LinkedListNode<KeyValuePair<TKey, TValue>>> dict;
    private readonly LinkedList<KeyValuePair<TKey, TValue>> list;

    #region constructor

    public LinkedHashMap()
    {
        dict = new Dictionary<TKey, LinkedListNode<KeyValuePair<TKey, TValue>>>();
        list = new LinkedList<KeyValuePair<TKey, TValue>>();
    }

    public LinkedHashMap(IEqualityComparer<TKey> comparer)
    {
        dict = new Dictionary<TKey, LinkedListNode<KeyValuePair<TKey, TValue>>>(comparer);
        list = new LinkedList<KeyValuePair<TKey, TValue>>();
    }

    public LinkedHashMap(int capacity)
    {
        dict = new Dictionary<TKey, LinkedListNode<KeyValuePair<TKey, TValue>>>(capacity);
        list = new LinkedList<KeyValuePair<TKey, TValue>>();
    }

    public LinkedHashMap(int capacity, IEqualityComparer<TKey> comparer)
    {
        dict = new Dictionary<TKey, LinkedListNode<KeyValuePair<TKey, TValue>>>(capacity, comparer);
        list = new LinkedList<KeyValuePair<TKey, TValue>>();
    }

    public LinkedHashMap(IEnumerable<KeyValuePair<TKey, TValue>> source)
    {
        if (source == null)
        {
            throw new ArgumentNullException("source");
        }
        var countable = source as System.Collections.ICollection;
        if (countable != null)
        {
            dict = new Dictionary<TKey, LinkedListNode<KeyValuePair<TKey, TValue>>>(countable.Count);
        }
        else
        {
            dict = new Dictionary<TKey, LinkedListNode<KeyValuePair<TKey, TValue>>>();
        }
        list = new LinkedList<KeyValuePair<TKey, TValue>>();
        foreach (var pair in source)
        {
            this[pair.Key] = pair.Value;
        }
    }

    public LinkedHashMap(IEnumerable<KeyValuePair<TKey, TValue>> source, IEqualityComparer<TKey> comparer)
    {
        if (source == null)
        {
            throw new ArgumentNullException("source");
        }
        var countable = source as System.Collections.ICollection;
        if (countable != null)
        {
            dict = new Dictionary<TKey, LinkedListNode<KeyValuePair<TKey, TValue>>>(countable.Count, comparer);
        }
        else
        {
            dict = new Dictionary<TKey, LinkedListNode<KeyValuePair<TKey, TValue>>>(comparer);
        }
        list = new LinkedList<KeyValuePair<TKey, TValue>>();
        foreach (var pair in source)
        {
            this[pair.Key] = pair.Value;
        }
    }

    #endregion

    #region IDictionary implementation

    public bool ContainsKey(TKey key)
    {
        return dict.ContainsKey(key);
    }

    public void Add(TKey key, TValue value)
    {
        DoAdd(key, value);
    }

    private void DoAdd(TKey key, TValue value)
    {
        var pair = new KeyValuePair<TKey, TValue>(key, value);
        var node = new LinkedListNode<KeyValuePair<TKey, TValue>>(pair);
        dict.Add(key, node);
        list.AddLast(node);
    }

    public bool Remove(TKey key)
    {
        LinkedListNode<KeyValuePair<TKey, TValue>> n;
        if (!dict.TryGetValue(key, out n))
        {
            return false;
        }
        DoRemove(n);
        return true;
    }

    private void DoRemove(LinkedListNode<KeyValuePair<TKey, TValue>> node)
    {
        dict.Remove(node.Value.Key);
        list.Remove(node);
    }

    public bool TryGetValue(TKey key, out TValue value)
    {
        LinkedListNode<KeyValuePair<TKey, TValue>> n;
        if (dict.TryGetValue(key, out n))
        {
            value = n.Value.Value;
            return true;
        }
        value = default(TValue);
        return false;
    }

    private bool TryGetNode(TKey key, TValue value, out LinkedListNode<KeyValuePair<TKey, TValue>> node)
    {
        LinkedListNode<KeyValuePair<TKey, TValue>> n;
        if (dict.TryGetValue(key, out n) && EqualityComparer<TValue>.Default.Equals(value, n.Value.Value))
        {
            node = n;
            return true;
        }
        node = null;
        return false;
    }

    public TValue this[TKey key]
    {
        get { return dict[key].Value.Value; }
        set
        {
            LinkedListNode<KeyValuePair<TKey, TValue>> n;
            if (!dict.TryGetValue(key, out n))
            {
                DoAdd(key, value);
                return;
            }
            DoSet(n, key, value);
        }
    }

    private void DoSet(LinkedListNode<KeyValuePair<TKey, TValue>> node, TKey key, TValue value)
    {
        var pair = new KeyValuePair<TKey, TValue>(key, value);
        var newNode = new LinkedListNode<KeyValuePair<TKey, TValue>>(pair);
        dict[key] = newNode;
        list.AddAfter(node, newNode);
        list.Remove(node);
    }

    public ICollection<TKey> Keys
    {
        get
        {
            return list.Select(p => p.Key).ToArray();
        }
    }

    public ICollection<TValue> Values
    {
        get
        {
            return list.Select(p => p.Value).ToArray();
        }
    }

    #endregion

    #region ICollection implementation

    public void Clear()
    {
        dict.Clear();
        list.Clear();
    }

    public int Count
    {
        get { return dict.Count; }
    }

    public bool IsReadOnly
    {
        get { return false; }
    }

    #endregion

    #region IEnumerable implementation

    public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
    {
        return list.GetEnumerator();
    }

    #endregion

    #region IEnumerable implementation

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

    #endregion

    #region explicit ICollection implementation

    void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item)
    {
        Add(item.Key, item.Value);
    }

    bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item)
    {
        LinkedListNode<KeyValuePair<TKey, TValue>> pair;
        return TryGetNode(item.Key, item.Value, out pair);
    }

    void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
    {
        list.CopyTo(array, arrayIndex);
    }

    bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item)
    {
        LinkedListNode<KeyValuePair<TKey, TValue>> node;
        if (!TryGetNode(item.Key, item.Value, out node))
        {
            return false;
        }
        DoRemove(node);
        return true;
    }

    #endregion
}
18
16
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
18
16